1. 程式人生 > >a,b,c三個執行緒按順序列印數字1-96 執行緒a列印1,b列印2,c列印3

a,b,c三個執行緒按順序列印數字1-96 執行緒a列印1,b列印2,c列印3

程式的主入口

公共的物件鎖

列印方法的核心執行緒

具體的實現程式碼 PrintThread  

public class PrintThread implements Runnable {
    private String name;//執行緒名稱
    private CommonLock commonLock;//公共鎖
    private String next;//下一個執行緒
    public PrintThread(String name, CommonLock commonLock,String next) {
        this.name = name;
        this.commonLock = commonLock;
        this.next = next;
    }
    @Override
    public void run() {
        while (true) {
            synchronized (commonLock){
                if(this.name.equals(commonLock.activeName)){
                    int count = commonLock.count.incrementAndGet();
                    if (count>96) {
                        commonLock.activeName = next;
                        commonLock.notifyAll();
                        break;
                    }else {
                        System.out.println("name=" + name + " count=" + count);
                        commonLock.activeName = next;
                        commonLock.notifyAll();
                    }
                }else{
                    try {
                        commonLock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

CommonLock公共鎖

import java.util.concurrent.atomic.AtomicInteger;

public class CommonLock {
    public AtomicInteger count=new AtomicInteger(0);//default
    public String activeName="a";//預設為a
}

 main方法入口

public class ThreadTest {
    public static void main(String[] args) {
        CommonLock commonLock = new CommonLock();
        Thread threada = new Thread(new PrintThread("a", commonLock, "b"));
        Thread threadb = new Thread(new PrintThread("b", commonLock, "c"));
        Thread threadc = new Thread(new PrintThread("c", commonLock, "a"));
        threada.start();
        threadb.start();
        threadc.start();
    }
}