控制三個線程依次對一個字符串末尾添加字母
- 2019 年 10 月 10 日
- 筆記
題目描述:
控制三個線程,按順序在「Hello」字符串後添加「_A」,「_B」,"_C" ,輸出 「Hello_A_B_C」;
實現方法:使用wait()和notifyAll()方法實現;
核心思想:在A線程運行完成時,同時設置B線程執行的條件,並喚醒(使用notifyAll())其他所有阻塞的線程,當A線程執行完後,如果獲得CPU時間片的線程是B線程,則執行,如果不是,則使用wait()方法讓該線程掛起。這樣就可以保證線程執行的順序。
運行結果:

代碼:
/** * */ package com.cherish.createThread; import java.util.Scanner; import java.util.concurrent.Callable; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * @author CherishTheYouth * */ public class TongCheng{ public static void main(String[] args) { TongCheng tc = new TongCheng(); HelloABC hello = tc.new HelloABC("hello"); ExecutorService es = Executors.newFixedThreadPool(3); es.execute(tc.new PrintThread(hello,"A") ); es.execute(tc.new PrintThread(hello,"B") ); es.execute(tc.new PrintThread(hello,"C") ); es.shutdown(); } public class HelloABC{ private String str = null; private String nextStr = "A"; //用於控制線程調用的順序 public HelloABC(String str) { this.str = str; } public void print() { System.out.println(str); } public String getString() { return str; } public void setString(String s) { str = new StringBuffer(str).append("_").append(s).toString(); } public void setNextString(String current) { switch(current) { case "A": nextStr = "B"; break; case "B": nextStr = "C"; break; case "C" : nextStr = "A"; break; } } } public class PrintThread implements Runnable{ private HelloABC hello = null; private String letter; public PrintThread(HelloABC hello,String letter) { this.hello = hello; this.letter = letter; } @Override public void run() { // TODO 自動生成的方法存根 for(int i = 0;i< 3;i++) { synchronized (hello) { if(hello.nextStr.equals(letter)) { hello.setString(letter); hello.setNextString(letter); hello.print(); hello.notifyAll(); }else { try { hello.wait(); } catch (InterruptedException e) { // TODO: handle exception e.printStackTrace(); } } } } } } }