多线程20个奇偶数一组交替打印

问题描述:

多线程打印20个偶数20个奇数为一组交替打印;


/**
 * 多线程打印
 * 先打印20个偶数在打印20个奇数依次循环交替
 * @author dongfen
 *
 */
public class EOdd {

	public static void main(String[] args) {
		Num1 num = new Num1(1000);
		Thread edd = new Thread(new EddThread1(num));
		edd.setName("edd");
		edd.start();
		Thread odd = new Thread(new OddThread1(num));
		odd.setName("odd");
		odd.start();
	}
	
}

class Num1{
	private static final ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>(){
		@Override
		protected Integer initialValue() {
			// TODO Auto-generated method stub
			return 0;
		}
		
	};
	
	private int max;
	public Num1(int max){
		this.max = max;
	}
	
	public synchronized void printEdd(){
		for(int i = 0; i< max;i+=2){
			System.out.println(Thread.currentThread().getName() + "      " + i);
			threadLocal.set(threadLocal.get()+1);
			if(threadLocal.get() % 20 == 0){
				waitFor();
			}
		}
		notifyAllThread();
		
	}

	private void notifyAllThread() {
		try {
			this.notifyAll();
			Thread.sleep(1000);
			
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void waitFor() {
		this.notifyAll();
		try {
			this.wait();
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public synchronized void printOdd(){
		for(int i = 1; i< max;i+=2){
			System.out.println(Thread.currentThread().getName() + "      " + i);
			threadLocal.set(threadLocal.get()+1);
			if(threadLocal.get() % 20 == 0){
				waitFor();
			}
		}
		notifyAllThread();
	}
	
}

class EddThread1 implements Runnable{

	private Num1 num;
	public EddThread1(Num1 num){
		this.num = num;
	}
	
	public void run() {
			this.num.printEdd();
	}
	
}

class OddThread1 implements Runnable{

	private Num1 num;
	public OddThread1(Num1 num){
		this.num = num;
	}
	
	public void run() {
		this.num.printOdd();
	}
	
}

参考资料地址: Java 多线程 子线程 交替打印 奇偶数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值