1. 程式人生 > 實用技巧 >用程式碼實現兩個執行緒交替列印0-100的奇偶數

用程式碼實現兩個執行緒交替列印0-100的奇偶數

  1. 用synchronized關鍵字實現

/**

  • 用程式碼實現兩個執行緒交替列印0-100的奇偶數,用synchronized關鍵字實現
    */

public class WaitNotifyPrintOddEvenSyn {
//2個執行緒
//一個處理偶數,一個處理奇數(使用位運算)
//用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){
//使用位運算 0代表偶數,1代表奇數
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){
                    //使用位運算  0代表偶數,1代表奇數
                    if((count & 1) == 1){
                        System.out.println(Thread.currentThread().getName()+":"+count++);
                    }
                }
            }
        }
    },"奇數").start();
}

}

  1. 使用wait/notify

/**

  • 兩個執行緒交替列印0~100奇偶數,用wait/notify
    */
    public class WaitNotifyPrintOddEveWait {
    //1.拿到鎖就列印
    //2.列印完,喚醒其他執行緒,就休眠
    private static int count =0;
    private static final Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {
    Thread thread = new Thread(new TurningRunner(),"偶數");
    Thread thread1 = new Thread(new TurningRunner(),"奇數");
    thread.start();
    Thread.sleep(10);//稍作休眠,防止執行緒啟動的順序不一致
    thread1.start();
    }

    static class TurningRunner implements Runnable{
    @Override
    public void run() {
    while (count<=100){
    synchronized (lock){
    //拿到鎖就列印
    System.out.println(Thread.currentThread().getName()+":"+count++);
    //只有兩個執行緒,所以喚醒使用notify和notifAll 一樣,喚醒那個睡眠的鎖
    lock.notify();
    if(count<=100){
    try {
    //如果任務還沒結束,就讓出當前的鎖,讓自己去休眠
    lock.wait();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }
    }
    }
    }

}