运行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