運行main函數實際上運行了一個線程,當在main中運行子線程時,兩個線程同時運行,所以有時涉及到同步與互斥,下面程序顯示這種情況。
class WN{
public static void main(String[] args){
ThreadB b=new ThreadB();
b.start();
System.out.println("b is start....");
synchronized(b)
{
try{
System.out.println("Waiting for b to complete...");
b.wait();
System.out.println("Completed.Now back to main thread");
}catch (InterruptedException e){}
}
System.out.println("Total1 is :"+b.total);
}
}
class ThreadB extends Thread {
int total;
public void run(){
try {
this.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(this){
System.out.println("ThreadB is running..");
for (int i=0;i<100000;i++ ){
total +=i;
}
System.out.println("Total2 is :"+total);
notify();
}
}
}
這裡我控制子線程延遲1秒執行。
另外notify函數是通知處於wait中的線程在notify所在的synchronized代碼塊執行結束後才繼續運行。
運行結果如下:
b is start....
Waiting for b to complete...
ThreadB is running..
Total2 is :704982704
Completed.Now back to main thread
Total1 is :704982704