面试题 多线程 顺序操作

问题

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值