面試題 多執行緒 順序操作
阿新 • • 發佈:2018-10-31
問題
編寫一個程式,程式會啟動4個執行緒,向4個檔案A,B,C,D裡寫入資料,每個執行緒只能寫一個值。
執行緒A:只寫1
執行緒B:只寫2
執行緒C:只寫3
執行緒D:只寫4
4個檔案A,B,C,D。
程式執行起來,4個檔案的寫入結果如下:
A:12341234...
B:23412341...
C:34123412...
D:41234123...
不解釋,直接上程式碼
import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; /** * * @author songjca * */ public class MyThreadSEQ extends Thread { private String name; private char outchar; private MyThreadSEQ next = null; private Queue<FileOutputStream> outSet = new ConcurrentLinkedQueue<FileOutputStream>(); public MyThreadSEQ(char outchar) { this.outchar = outchar; this.name = "thread" + this.outchar; } public char getOutchar() { return this.outchar; } public void setOutchar(char outchar) { this.outchar = outchar; } public MyThreadSEQ getNext() { return this.next; } public void setNext(MyThreadSEQ next) { this.next = next; } public Queue<FileOutputStream> getOutSet() { return this.outSet; } public void addOut(FileOutputStream out) { this.outSet.add(out); } @Override public void run() { try { while (true) { int i = 0; while (this.outSet.size() != 0) { FileOutputStream out = this.outSet.poll(); synchronized (out) { System.out.println("----------" + name + " start ---------"); out.write(this.outchar); i = i + 1; if (i == 4) { out.write('\r'); out.write('\n'); i = 0; } out.flush(); this.next.addOut(out); out.notifyAll(); System.out.println("----------" + name + " end ---------"); } } } } catch (Exception e) { e.printStackTrace(); } } public static void main(String... args) { try { MyThreadSEQ t1 = new MyThreadSEQ('1'); MyThreadSEQ t2 = new MyThreadSEQ('2'); MyThreadSEQ t3 = new MyThreadSEQ('3'); MyThreadSEQ t4 = new MyThreadSEQ('4'); t1.setNext(t2); t2.setNext(t3); t3.setNext(t4); t4.setNext(t1); FileOutputStream out1 = new FileOutputStream("d:/a.txt"); FileOutputStream out2 = new FileOutputStream("d:/b.txt"); FileOutputStream out3 = new FileOutputStream("d:/c.txt"); FileOutputStream out4 = new FileOutputStream("d:/d.txt"); t1.addOut(out1); t2.addOut(out2); t3.addOut(out3); t4.addOut(out4); t1.start(); t2.start(); t3.start(); t4.start(); } catch (FileNotFoundException e) { // e.printStackTrace(); } finally { } } }