wait 、notify 、join、yield

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对于保证操作的原子性有非常大的帮助。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

powerfuler

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值