標籤:

線程間的通訊[基礎]

package ThreadDemo;/** * 線程間的通訊: * 多個線程處理資源,但任務不同 * Created by admin on 2018/4/28. *///資源class Resource { String name ; String sex;}//輸入class Input implements Runnable{ Resource t ; Input(Resource t){ this.t = t; } public void run(){ int x = 0;//這裡面不同步,所以一直輸入 synchronized (t) { while (true) { if (x == 0) { t.name = "iooioi"; t.sex = "psvm"; } else { t.name = "麗麗"; t.sex = "女"; } x = (x + 1) % 2; } } }}//輸出class Output implements Runnable{ Resource t ; Output(Resource t){ this.t = t; } public void run(){ // synchronized (t){ while (true){ System.out.println(t.name+"........."+t.sex); } // } }}class threadExampleDemo{ public static void main(String[] args) { //創建資源 Resource t = new Resource(); //創建任務 Input in = new Input(t); Output out = new Output(t); //創建線程,執行路徑 Thread t1 = new Thread(in); Thread t2 = new Thread(out); //開啟線程 t1.start(); t2.start(); }}

推薦閱讀:

如何利用秒級監控進行mongodb故障排查
進程
夏周:阿里雲 Redis 容災體系介紹
找到Linux虛機Load高的"元兇"

TAG:多線程 | 線程 |