wait 、notify 、join、yield

来源:互联网 发布:知乎 东风 编辑:程序博客网 时间:2024/06/03 18:20
wait 和 notify 的例子


public class SimpleWN {
final static Object object = new Object();


public static class T1 extends Thread {
public void run() {
synchronized (object) {
System.out.println(System.currentTimeMillis() + ":T1 start!");


try {
System.out.println(System.currentTimeMillis()
+ ":T1 wait for object!");
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(System.currentTimeMillis() + ":T1 end!");
}
}
}


public static class T2 extends Thread {
public void run() {
synchronized (object) {
System.out.println(System.currentTimeMillis()
+ ":T2 start! notify one thread。");
object.notify();
System.out.println(System.currentTimeMillis() + ":T2 end!");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
}
}
}


public static void main(String[] args) {
Thread t1 = new T1();
Thread t2 = new T2();
t1.start();
t2.start();
}
}




1498132782164:T1 start!
1498132782164:T1 wait for object!
1498132782164:T2 start! notify one thread。
1498132782164:T2 end!
1498132784177:T1 end!


可以看出:T2通知T1执行后,T1不能立即执行,而是等待T2释放object锁,并重新获得锁后,才能继续执行。


join与yield的例子


public class joinMain {
public volatile static int i = 0;


public static class AddThread extends Thread {


@Override
public void run() {
for (i = 0; i < 100000; i++);
}


}


public static void main(String[] args) throws InterruptedException {
AddThread at = new AddThread();
at.start();
at.join();
System.out.println(i);
}
}


主函数,如果不使用join()等待AddThread,那么得到的i是0或者是很小的值,因为AddThread还没执行,i已经被输出了。但加入join后,标识主函数愿意等待AddThread执行完,跟着AddThread一起走,所有输出i=100000。


Thread.yield()一旦执行,它会使当前线程让出cpu(并不放弃cpu),让出后,还会进行cpu资源争夺,能否在分到资源就不一定了。意思就是说要歇一会,给其他线程更多的机会。



volatile对于保证操作的原子性有非常大的帮助。




原创粉丝点击