不太好的方法:用synchronized实现
当其中一个线程一直持有锁时,会重复执行 if 判断,做无用功!
/**
* 两个线程交替打印0-100的奇偶数,
* 用synchronized关键字实现
*/
public class WaitNotifyPrintOddEvenSyn {
// 新建2个线程
// 1个只处理偶数,第二个只处理奇数(用位运算)
// 用synchronized来通信
private static int count;
private static final Object lock = new Object();
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
while (count < 100) {
synchronized (lock) {
if ((count & 1) == 0) {
System.out.println(Thread.currentThread().getName() + ":" + count++);
}
}
}
}
}, "偶数线程").start();
new Thread(new Runnable() {
@Override
public void run() {
while (count < 100) {
synchronized (lock) {
if ((count & 1) == 1) {
System.out.println(Thread.currentThread().getName() + ":" + count++);
}
}
}
}
}, "奇数线程").start();
}
}
更好的实现方法:用wait和notify实现
/**
* 两个线程交替打印0-100的奇偶数,
* 用wait和notify实现
*/
public class WaitNotifyPrintOddEvenWait {
// 1.拿到锁,就打印
// 2.打印完,唤醒其它线程,自己休眠
private static int count = 0;
private static final Object lock = new Object();
static class TurningRunner implements Runnable {
@Override
public void run() {
while (count <= 100) {
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + ":" + count++);
lock.notify();
if (count <= 100) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public static void main(String[] args) {
new Thread(new TurningRunner(), "偶数线程").start();
new Thread(new TurningRunner(), "奇数线程").start();
}
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。