多线程轮流打印

三个线程,分别只用以打印a,b,c

用多线程实现打印abc重复10次


我想了一个比较丑的方法,就是一个命令者,用以发布命令,这次要打印那个字符,三个打印者就分别检查这个指令是否是发给自己的


class ShId {
	private int value;
	public ShId(int id) {
		value = id;
	}
	
	public void set(int i) {
		value = i;
	}
	
	public boolean isEqual(Integer i) {
		return i.intValue() == value;
	}
	
	@Override
	public boolean equals(Object o) {
		if (this == o) return true;
		return ((ShId)o).value == value;
	}
}

class Work implements Runnable {
	
	private String name;
	private Integer id;
	private ShId shId;
	
	
	public Work(String name, Integer id, ShId shId) {
		this.name = name;
		this.id = id;
		this.shId = shId;
	}
	
	@Override
	public void run() {
		try {
            while (true) {
			synchronized (shId) {
				while(!shId.isEqual(id)) {
					shId.wait();
				}
				System.out.print(name);
				shId.set(-1);
				shId.notifyAll();
				if (name.equals("c")) System.out.println();
			}
            }
		} catch(InterruptedException e) {
			e.printStackTrace();
		}
	}
}

class Produce implements Runnable {
	
	private int count;
	private ShId shId;
	
	public Produce (int count, ShId shId) {
		this.count = count;
		this.shId = shId;
	}
	
	@Override
	public void run() {
		try {
			while (count >0) {
				for (int i = 0; i < 3; ++i) {
					synchronized (shId) {
						while (!shId.isEqual(new Integer(-1))) {
							shId.wait();
						}
						shId.set(i);
						shId.notifyAll();
					}
				}
				--count;
			}
		} catch (InterruptedException e) {
			
		}
	}
}

public class testt {
    public static void main(String[] args) {
       
    	ShId shId = new ShId(-1);
    	Work w1 = new Work("a",0, shId);
    	Work w2 = new Work("b",1, shId);
    	Work w3 = new Work("c",2, shId);
    	Produce p = new Produce(10, shId);
    	
        new Thread(w1, "work1").start();
        new Thread(w2, "work2").start();
        new Thread(w3, "work3").start();
        new Thread(p, "produce").start();
    }
}
 


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值