四個線程t1,t2,t3,t4,分別打印文字,t1只能打印1,t2只能打印2,t3只能打印3,t4只能打印4,打印如下A B C D內容: A:123412341234 B:234123412341

package t1t2t3t4;

/**
 * Created by Administrator on 2017/5/13.
 */
public class Main {
    public static void main(String[] args) {
        Object lock = new Object();
        for(int i=1;i<=4;i++){
           char str=(char) (64+i);
           System.out.print(str+":");
           NumberThread n = new NumberThread();
           n.state=i;
           Thread t1 = new Thread(n);
            t1.setName("線程1");
            Thread t2 = new Thread(n);
            t2.setName("線程2");
            Thread t3 = new Thread(n);
            t3.setName("線程3");
            Thread t4 = new Thread(n);
            t4.setName("線程4");
            t1.start();t2.start();t3.start();t4.start();
            try {
            Thread.sleep(500);
         } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
            System.out.println();
        }
        
    }
}
package t1t2t3t4;

/**
 * Created by Administrator on 2017/5/13.
 */
public class NumberThread implements Runnable {
    int count = 0;
    int state = 1; //記錄當前要執行的線程

    
    public void run() {
        while (true) {
            //傳對象,通過鎖這個對象,判斷資源的鎖定狀態
            synchronized (this) {
                //如果線程名中包含state,表示線程名正確,打印數字
                if (Thread.currentThread().getName().contains(state + "")) {
                    System.out.print(state);
                    //正確線程打印一次後,增加state,用於下次正確的線程打印
                    count++;
                    state++;
                }else{
                    //要運行的線程和state不一致,則休眠, 等待下次喚醒
                    try {
                        wait();
                    } catch (InterruptedException e) {

                    }
                }
                //state加到4,從1開始
                if (state == 5) {
                    state = 1;
                   //通知其他所有線程運行。不知道運行的是哪個線程
                }
                //喚醒所有線程
                notifyAll();
                if (count == 12) {                 
                    break;
                }
            }
        }
    }
}

運行結果:

A:123412341234
B:234123412341
C:341234123412
D:412341234123

發佈了54 篇原創文章 · 獲贊 68 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章