生活随笔
收集整理的這篇文章主要介紹了
多线程轮流打印
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
三個線程,分別只用以打印a,b,c
用多線程實現打印abc重復10次
我想了一個比較丑的方法,就是一個命令者,用以發布命令,這次要打印那個字符,三個打印者就分別檢查這個指令是否是發給自己的
class ShId {private int value;public ShId(int id) {value = id;}public void set(int i) {value = i;}public boolean isEqual(Integer i) {return i.intValue() == value;}@Overridepublic boolean equals(Object o) {if (this == o) return true;return ((ShId)o).value == value;}
}class Work implements Runnable {private String name;private Integer id;private ShId shId;public Work(String name, Integer id, ShId shId) {this.name = name;this.id = id;this.shId = shId;}@Overridepublic void run() {try {while (true) {synchronized (shId) {while(!shId.isEqual(id)) {shId.wait();}System.out.print(name);shId.set(-1);shId.notifyAll();if (name.equals("c")) System.out.println();}}} catch(InterruptedException e) {e.printStackTrace();}}
}class Produce implements Runnable {private int count;private ShId shId;public Produce (int count, ShId shId) {this.count = count;this.shId = shId;}@Overridepublic void run() {try {while (count >0) {for (int i = 0; i < 3; ++i) {synchronized (shId) {while (!shId.isEqual(new Integer(-1))) {shId.wait();}shId.set(i);shId.notifyAll();}}--count;}} catch (InterruptedException e) {}}
}public class testt {public static void main(String[] args) {ShId shId = new ShId(-1);Work w1 = new Work("a",0, shId);Work w2 = new Work("b",1, shId);Work w3 = new Work("c",2, shId);Produce p = new Produce(10, shId);new Thread(w1, "work1").start();new Thread(w2, "work2").start();new Thread(w3, "work3").start();new Thread(p, "produce").start();}
}
與50位技術專家面對面20年技術見證,附贈技術全景圖
總結
以上是生活随笔為你收集整理的多线程轮流打印的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。