線程同步輔助類,主要學習兩點:數組
Semphore s = new Semphore(2);
public class PrintQueue { private Semaphore semaphore; private boolean freePrinters[]; private Lock lockPrinters; public PrintQueue(){ semaphore=new Semaphore(3); freePrinters=new boolean[3]; for (int i=0; i<3; i++){ freePrinters[i]=true; } lockPrinters=new ReentrantLock(); } public void printJob (Object document){ try { semaphore.acquire(); int assignedPrinter=getPrinter(); Long duration=(long)(Math.random()*10); System.out.printf("%s: PrintQueue: Printing a Job in Printer %d during %d seconds\n",Thread.currentThread().getName(),assignedPrinter,duration); TimeUnit.SECONDS.sleep(duration); freePrinters[assignedPrinter]=true; } catch (InterruptedException e) { e.printStackTrace(); } finally { // Free the semaphore semaphore.release(); } } private int getPrinter() { int ret=-1; try { lockPrinters.lock(); for (int i=0; i<freePrinters.length; i++) { if (freePrinters[i]){ ret=i; freePrinters[i]=false; break; } } } catch (Exception e) { e.printStackTrace(); } finally { lockPrinters.unlock(); } return ret; } }
1 public class Job implements Runnable { 2 private PrintQueue printQueue; 3 4 public Job(PrintQueue printQueue){ 5 this.printQueue=printQueue; 6 } 7 8 @Override 9 public void run() { 10 System.out.printf("%s: Going to print a job\n",Thread.currentThread().getName()); 11 printQueue.printJob(new Object()); 12 System.out.printf("%s: The document has been printed\n",Thread.currentThread().getName()); 13 } 14 }
public static void main (String args[]){ PrintQueue printQueue=new PrintQueue(); Thread thread[]=new Thread[12]; for (int i=0; i<12; i++){ thread[i]=new Thread(new Job(printQueue),"Thread "+i); } for (int i=0; i<12; i++){ thread[i].start(); } }
public Semaphore(int permits, boolean fair)
1 public class VideoConference implements Runnable{ 2 private final CountDownLatch controller; 3 4 public VideoConference(int number) { 5 controller=new CountDownLatch(number); 6 } 7 public void arrive(String name){ 8 System.out.printf("%s has arrived.\n",name); 9 10 controller.countDown();//調用countDown()方法,使內部計數器減1 11 System.out.printf("VideoConference: Waiting for %d participants.\n",controller.getCount()); 12 } 13 14 @Override 15 public void run() { 16 System.out.printf("VideoConference: Initialization: %d participants.\n",controller.getCount()); 17 try { 18 19 controller.await();//等待,直到CoutDownLatch計數器爲0 20 21 System.out.printf("VideoConference: All the participants have come\n"); 22 System.out.printf("VideoConference: Let's start...\n"); 23 } catch (InterruptedException e) { 24 e.printStackTrace(); 25 } 26 } 27 }
1 public class Participant implements Runnable { 2 private VideoConference conference; 3 4 private String name; 5 6 public Participant(VideoConference conference, String name) { 7 this.conference=conference; 8 this.name=name; 9 } 10 @Override 11 public void run() { 12 Long duration=(long)(Math.random()*10); 13 try { 14 TimeUnit.SECONDS.sleep(duration); 15 } catch (InterruptedException e) { 16 e.printStackTrace(); 17 } 18 conference.arrive(name);//每到一我的員,CountDownLatch計數器就減小1 19 } 20 }
1 public static void main(String[] args) { 2 VideoConference conference = new VideoConference(10); 3 Thread threadConference = new Thread(conference); 4 threadConference.start();//開啓await()方法,在內部計數器爲0以前線程處於等待狀態 5 for (int i = 0; i < 10; i++) { 6 Participant p = new Participant(conference, "Participant " + i); 7 Thread t = new Thread(p); 8 t.start(); 9 } 10 }
1 public class Searcher implements Runnable { 2 private final CyclicBarrier barrier; 3 @Override 4 public void run() { 5 int counter; 6 System.out.printf("%s: Processing lines from %d to %d.\n",Thread.currentThread().getName(),firstRow,lastRow); 7 for (int i=firstRow; i<lastRow; i++){ 8 int row[]=mock.getRow(i); 9 counter=0; 10 for (int j=0; j<row.length; j++){ 11 if (row[j]==number){ 12 counter++; 13 } 14 } 15 results.setData(i, counter); 16 } 17 System.out.printf("%s: Lines processed.\n",Thread.currentThread().getName()); 18 try { 19 barrier.await(); 20 } catch (InterruptedException e) { 21 e.printStackTrace(); 22 } catch (BrokenBarrierException e) { 23 e.printStackTrace(); 24 } 25 } 26 }
1 public class Grouper implements Runnable { 2 private Results results; 3 4 public Grouper(Results results){ 5 this.results=results; 6 } 7 @Override 8 public void run() { 9 int finalResult=0; 10 System.out.printf("Grouper: Processing results...\n"); 11 int data[]=results.getData(); 12 for (int number:data){ 13 finalResult+=number; 14 } 15 System.out.printf("Grouper: Total result: %d.\n",finalResult); 16 } 17 }
1 public static void main(String[] args) { 2 final int ROWS=10000; 3 final int NUMBERS=1000; 4 final int SEARCH=5; 5 final int PARTICIPANTS=5; 6 final int LINES_PARTICIPANT=2000; 7 MatrixMock mock=new MatrixMock(ROWS, NUMBERS,SEARCH);//矩陣的聲明 8 9 Results results=new Results(ROWS);//結果集 10 11 Grouper grouper=new Grouper(results);//彙總線程 12 13 CyclicBarrier barrier=new CyclicBarrier(PARTICIPANTS,grouper);//柵欄,傳入參數含義:線程同步個數,彙總線程 14 15 Searcher searchers[]=new Searcher[PARTICIPANTS]; 16 for (int i=0; i<PARTICIPANTS; i++){ 17 searchers[i]=new Searcher(i*LINES_PARTICIPANT, (i*LINES_PARTICIPANT)+LINES_PARTICIPANT, mock, results, 5,barrier); 18 Thread thread=new Thread(searchers[i]); 19 thread.start(); 20 } 21 System.out.printf("Main: The main thread has finished.\n"); 22 }
Mock: There are 999286 ocurrences of number in generated data. Thread-0: Processing lines from 0 to 2000. Main: The main thread has finished. Thread-0: Lines processed. Thread-1: Processing lines from 2000 to 4000. Thread-1: Lines processed. Thread-3: Processing lines from 6000 to 8000. Thread-3: Lines processed. Thread-2: Processing lines from 4000 to 6000. Thread-2: Lines processed. Thread-4: Processing lines from 8000 to 10000. Thread-4: Lines processed. Grouper: Processing results... Grouper: Total result: 999286.
1 public class FileSearch implements Runnable { 2 private String initPath; 3 4 private String end; 5 6 private List<String> results; 7 8 private Phaser phaser; 9 10 public FileSearch(String initPath, String end, Phaser phaser) { 11 this.initPath = initPath; 12 this.end = end; 13 this.phaser=phaser; 14 results=new ArrayList<>(); 15 } 16 @Override 17 public void run() { 18 19 phaser.arriveAndAwaitAdvance();//等待全部的線程建立完成,確保在進行文件查找的時候全部的線程都已經建立完成了 20 21 System.out.printf("%s: Starting.\n",Thread.currentThread().getName()); 22 23 // 1st Phase: 查找文件 24 File file = new File(initPath); 25 if (file.isDirectory()) { 26 directoryProcess(file); 27 } 28 29 // 若是查找結果爲false,那麼就把該線程從Phaser中移除掉而且結束該線程的運行 30 if (!checkResults()){ 31 return; 32 } 33 34 // 2nd Phase: 過濾結果,過濾出符合條件的(一天內的)結果集 35 filterResults(); 36 37 // 若是過濾結果集結果是空的,那麼把該線程從Phaser中移除,不讓它進入下一階段的執行 38 if (!checkResults()){ 39 return; 40 } 41 42 // 3rd Phase: 顯示結果 43 showInfo(); 44 phaser.arriveAndDeregister();//任務完成,註銷掉全部的線程 45 System.out.printf("%s: Work completed.\n",Thread.currentThread().getName()); 46 } 47 private void showInfo() { 48 for (int i=0; i<results.size(); i++){ 49 File file=new File(results.get(i)); 50 System.out.printf("%s: %s\n",Thread.currentThread().getName(),file.getAbsolutePath()); 51 } 52 // Waits for the end of all the FileSearch threads that are registered in the phaser 53 phaser.arriveAndAwaitAdvance(); 54 } 55 private boolean checkResults() { 56 if (results.isEmpty()) { 57 System.out.printf("%s: Phase %d: 0 results.\n",Thread.currentThread().getName(),phaser.getPhase()); 58 System.out.printf("%s: Phase %d: End.\n",Thread.currentThread().getName(),phaser.getPhase()); 59 //結果爲空,Phaser完成並把該線程從Phaser中移除掉 60 phaser.arriveAndDeregister(); 61 return false; 62 } else { 63 // 等待全部線程查找完成 64 System.out.printf("%s: Phase %d: %d results.\n",Thread.currentThread().getName(),phaser.getPhase(),results.size()); 65 phaser.arriveAndAwaitAdvance(); 66 return true; 67 } 68 } 69 private void filterResults() { 70 List<String> newResults=new ArrayList<>(); 71 long actualDate=new Date().getTime(); 72 for (int i=0; i<results.size(); i++){ 73 File file=new File(results.get(i)); 74 long fileDate=file.lastModified(); 75 76 if (actualDate-fileDate<TimeUnit.MILLISECONDS.convert(1,TimeUnit.DAYS)){ 77 newResults.add(results.get(i)); 78 } 79 } 80 results=newResults; 81 } 82 private void directoryProcess(File file) { 83 // Get the content of the directory 84 File list[] = file.listFiles(); 85 if (list != null) { 86 for (int i = 0; i < list.length; i++) { 87 if (list[i].isDirectory()) { 88 // If is a directory, process it 89 directoryProcess(list[i]); 90 } else { 91 // If is a file, process it 92 fileProcess(list[i]); 93 } 94 } 95 } 96 } 97 private void fileProcess(File file) { 98 if (file.getName().endsWith(end)) { 99 results.add(file.getAbsolutePath()); 100 } 101 } 102 }
1 public static void main(String[] args) { 2 Phaser phaser = new Phaser(3); 3 4 FileSearch system = new FileSearch("C:\\Windows", "log", phaser); 5 FileSearch apps = new FileSearch("C:\\Program Files", "log", phaser); 6 FileSearch documents = new FileSearch("C:\\Documents And Settings", "log", phaser); 7 8 Thread systemThread = new Thread(system, "System"); 9 systemThread.start(); 10 Thread appsThread = new Thread(apps, "Apps"); 11 appsThread.start(); 12 Thread documentsThread = new Thread(documents, "Documents"); 13 documentsThread.start(); 14 try { 15 systemThread.join(); 16 appsThread.join(); 17 documentsThread.join(); 18 } catch (InterruptedException e) { 19 e.printStackTrace(); 20 } 21 System.out.printf("Terminated: %s\n", phaser.isTerminated()); 22 }