1. 程式人生 > 其它 >三個執行緒交替列印ABC

三個執行緒交替列印ABC

第一種方式:使用wait/notify實現

public class PrintABC1 {
    int state;//狀態量,指示執行緒交替
    int times;//每個執行緒列印次數
    private static final Object lock=new Object();

    public void printABC1(int times){
        this.times=times;
    }

    public void print(String str,int target){
        for(int i=0;i<times;i++){
            
synchronized (PrintABC1.class){ if (state % 3 == target){ state++; try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } notifyAll(); } } }
public static void main(String[] args){ printABC printABC=new printABC(3); Thread t1=new Thread(()->{ printABC.print("A",0); }); Thread t2=new Thread(()->{ printABC.print("B",1); }); Thread t3=new Thread(()->{ printABC.print(
"C",2); }); t1.start(); t2.start(); t3.start(); } }

第二種方式:使用ReentrantLock實現

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class printABC {
    private int times;
    private int state;
    Lock lock=new ReentrantLock();

    public printABC(int times){
        this.times=times;
    }

    public void print(String str,int target){
        for(int i=0;i<times;){
            if (state % 3 == target){
                lock.lock();
                System.out.println(str);
                state++;
                i++;//重點,i++如果寫在for迴圈中就會導致當if條件不滿足時直接進入下一次迴圈,無法實現交替功能
                    //寫在被鎖住的程式碼塊之間使得只有在滿足if條件時,才有i++
                lock.unlock();
            }
        }
    }

    public static void main(String[] args){
        printABC printABC=new printABC(3);
        Thread t1=new Thread(()->{
            printABC.print("A",0);
        });
        Thread t2=new Thread(()->{
            printABC.print("B",1);
        });
        Thread t3=new Thread(()->{
            printABC.print("C",2);
        });
        t1.start();
        t2.start();
        t3.start();

    }

}