Tuesday 16 June 2015

Part 2. Thread in java: method revisiting

From previous post, we have understood how to create threads in Java. In this post, I would introduce some meaning methods, and how to make it synchronization & wait/notify mechanism.
Thread method revisiting
  1. Sleep: sleep the current thread in millseconds.
try {
Thread.sleep(500);// Sleeping in 0.5 second
} catch (InterruptedException e) {
}
  1. Join method
This method helps current thread (caller thread) will wait until this thread finished execution. There are three signals:
join()
join(long millis)
join(long millis, int nanos)
For example:
try{
pn2.join();
}catch(Exception e){}
System.out.println("This line is reached!!!");
In this example, current thread will only continually executed when thread “pn2” is finished (die). That means, the line “This line is reached!!!” is displayed after pn2 thread die.
Example codes:
package threads;

public class PrintNumber_1 implements Runnable{
int x = 20;
public PrintNumber_1(int x) {
this.x = x;
}
@Override
public void run() {
for(int i=0; ii++){
System.out.println("I'm : " + i+", of "+this.getClass().getName());
try {
Thread.sleep(500);//Sleeping in 0.5 second
} catch (InterruptedException e) {
}
}
}
}
package threads;

public class PrintNumber_2 extends Thread {
int x;
public PrintNumber_2(int x) {
this.x = x;
}
@Override
public void run() {
for (int i = 0; i < x; i++) {
System.out.println("I'm : " + i + ", of "
+ this.getClass().getName());
try {
Thread.sleep(500);// Sleeping in 0.5 second
} catch (InterruptedException e) {
}
}
}
}
public class ThreadDemo {
public static void main(String[] args){
int count=10;
PrintNumber_1 pn1 = new PrintNumber_1(count);
Thread tpn = new Thread(pn1);
tpn.start();
System.out.println("PrintNumber_1 thread is started....");
PrintNumber_2 pn2 = new PrintNumber_2(count);
pn2.start();
System.out.println("PrintNumber_2 thread is started....");
try{
pn2.join();
}catch(Exception e){}
System.out.println("This line is reached!!!");
}
}
Output:


  1. Daemon thread
Daemon thread is a thread that runs on background of the program. When program finished (all other threads die), the daemon thread will immediately finish themselves.
For example: we set thread PrintNumber_2 is daemon:
public static void main(String[] args){
int count=10;
PrintNumber_2 pn2 = new PrintNumber_2(count);
pn2.setDaemon(true);
pn2.start();
System.out.println("PrintNumber_2 thread is started....");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
System.out.println("Main finished!");
}
Output: the thread PrintNumber_2 will finish immediately after other user threads die. If we didnot set PrintNumber_2 to daemon, it will print all the number.


No comments:

Post a Comment