面试题 多线程 顺序操作

来源:互联网 发布:星达字段拼凑软件 编辑:程序博客网 时间:2024/04/30 16:21

问题

编写一个程序,程序会启动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);}@Overridepublic 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 {}}}


0 0
原创粉丝点击