How to perform multiple tasks by multiple threads (multitasking in multithreading)?
If you have to perform multiple tasks by multiple threads,have multiple run() methods.For example: Program of performing two tasks by two threads
- class Simple1 extends Thread{
- public void run(){
- System.out.println("task one");
- }
- }
- class Simple2 extends Thread{
- public void run(){
- System.out.println("task two");
- }
- }
- class TestMultitasking3{
- public static void main(String args[]){
- Simple1 t1=new Simple1();
- Simple2 t2=new Simple2();
- t1.start();
- t2.start();
- }
- }
Output:task one task two
How to perform single task by multiple threads?
- class TestMultitasking1 extends Thread{
- public void run(){
- System.out.println("task one");
- }
- public static void main(String args[]){
- TestMultitasking1 t1=new TestMultitasking1();
- TestMultitasking1 t2=new TestMultitasking1();
- TestMultitasking1 t3=new TestMultitasking1();
- t1.start();
- t2.start();
- t3.start();
- }
- }
Output:task one task one task one
- class TestMultitasking2 implements Runnable{
- public void run(){
- System.out.println("task one");
- }
- public static void main(String args[]){
- Thread t1 =new Thread(new TestMultitasking2());//passing annonymous object of TestMultitasking2 class
- Thread t2 =new Thread(new TestMultitasking2());
- t1.start();
- t2.start();
- }
- }
Output:task one task one
Note: Each thread run in a separate callstack.
What if we call run() method directly instead start() method?
|
- class TestCallRun1 extends Thread{
- public void run(){
- System.out.println("running...");
- }
- public static void main(String args[]){
- TestCallRun1 t1=new TestCallRun1();
- t1.run();//fine, but does not start a separate call stack
- }
- }
Output:running...
Problem if you direct call run() method
- class TestCallRun2 extends Thread{
- public void run(){
- for(int i=1;i<5;i++){
- try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
- System.out.println(i);
- }
- }
- public static void main(String args[]){
- TestCallRun2 t1=new TestCallRun2();
- TestCallRun2 t2=new TestCallRun2();
- t1.run();
- t2.run();
- }
- }
Output:1 2 3 4 5 1 2 3 4 5
Can we start a thread twice ?
No. After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception.
Let's understand it by the example given below:
- public class TestThreadTwice1 extends Thread{
- public void run(){
- System.out.println("running...");
- }
- public static void main(String args[]){
- TestThreadTwice1 t1=new TestThreadTwice1();
- t1.start();
- t1.start();
- }
- }
- Output:
running Exception in thread "main" java.lang.IllegalThreadStateException
Broadcast receiver runs in which thread, by default?
By default every component of android run on main thread (UI thread) so broadcast receiver by default runs on Main thread.
How many types of memory areas are allocated by JVM?
Many types:
* Class(Method) Area
* Heap
* Stack
* Program Counter Register
* Native Method Stack
What is difference between JDK,JRE and JVM?
JVM
JVM is an acronym for Java Virtual Machine, it is an abstract machine which provides the runtime environment in which java bytecode can be executed. It is a specification.
JVMs are available for many hardware and software platforms (so JVM is platform dependent).
JRE
JRE stands for Java Runtime Environment. It is the implementation of JVM.
JDK
JDK is an acronym for Java Development Kit. It physically exists. It contains JRE + development tools.
Important methods of StringBuffer class
public synchronized StringBuffer append(String s): is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc.
public synchronized StringBuffer insert(int offset, String s): is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc.
public synchronized StringBuffer replace(int startIndex, int endIndex, String str): is used to replace the string from specified startIndex and endIndex.
public synchronized StringBuffer delete(int startIndex, int endIndex):is used to delete the string from specified startIndex and endIndex.
public synchronized StringBuffer reverse(): is used to reverse the string.
public int capacity(): is used to return the current capacity.
public void ensureCapacity(int minimumCapacity): is used to ensure the capacity at least equal to the given minimum.
public char charAt(int index): is used to return the character at the specified position.
public int length(): is used to return the length of the string i.e. total number of characters.
public String substring(int beginIndex): is used to return the substring from the specified beginIndex.
public String substring(int beginIndex, int endIndex): is used to return the substring from the specified beginIndex and endIndex.
Java String class methods
The java.lang.String class provides a lot of methods to work on string. By the help of these methods, we can perform operations on string such as trimming, concatenating, converting, comparing, replacing strings etc.
Java String is a powerful concept because everything is treated as a string if you submit any form in window based, web based or mobile application.
Let's see the important methods of String class.
Java String toUpperCase() and toLowerCase() method
The java string toUpperCase() method converts this string into uppercase letter and string toLowerCase() method into lowercase letter.
String s="Sachin"; System.out.println(s.toUpperCase());//SACHIN System.out.println(s.toLowerCase());//sachin System.out.println(s);//Sachin(no change in original)
Output
SACHIN sachin Sachin
Java String trim() method
The string trim() method eliminates white spaces before and after string.
String s=" Sachin "; System.out.println(s);// Sachin System.out.println(s.trim());//Sachin
Output
Sachin Sachin
Java String startsWith() and endsWith() method
String s="Sachin"; System.out.println(s.startsWith("Sa"));//true System.out.println(s.endsWith("n"));//true
Output
true true
Java String charAt() method
The string charAt() method returns a character at specified index.
String s="Sachin"; System.out.println(s.charAt(0));//S System.out.println(s.charAt(3));//h
Output
S h
Java String length() method
The string length() method returns length of the string.
String s="Sachin"; System.out.println(s.length());//6
Output
6
Java String intern() method
A pool of strings, initially empty, is maintained privately by the class String.
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
String s=new String("Sachin"); String s2=s.intern(); System.out.println(s2);//Sachin
Output
Sachin
Java String valueOf() method
The string valueOf() method coverts given type such as int, long, float, double, boolean, char and char array into string.
int a=10; String s=String.valueOf(a); System.out.println(s+10);
Output:
1010
Java String replace() method
The string replace() method replaces all occurrence of first sequence of character with second sequence of character.
String s1="Java is a programming language. Java is a platform. Java is an Island."; String replaceString=s1.replace("Java","Kava");//replaces all occurrences of "Java" to "Kava" System.out.println(replaceString);
Output:
Kava is a programming language. Kava is a platform. Kava is an Island
Are there any other classes whose objects are immutable?
Yes, classes like Character, Byte, Integer, Float, Double, Long... called Wrapper classes are immutable. Classes like BigInteger, BigDecimal are also immutable.
What is the difference between String and StringBuffer classes?
String class objects are immutable and hence their contents cannot modified whereas StringBuffer class objects are mutable, so they can be modified.
Moreover the methods that directly manipulate data of the objects are not available in String class and such methods are available in StringBuffer class.
Explain the difference between the following two statements
1) String s = "Hello":
2) String s = new String (" Hello");
In the first statement, assignment operator is used to assign the string literal to the String variable s. In this case, JVM first of all checks whether the same object is already available in the string constant pool. If it is available, then it creates another reference to it. If the same object is not available then it creates another object with the content "Hello" and stores it into the string constant pool.
In the second statement, new operator is used create the string object. In this case, JVM always creates a new object without looking in the string constant pool.
What is object reference?
Object reference is a unique hexadecimal number representing the memory address of the object. It is useful to access the members of the object.