不太好的方法:用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();
}
}
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。