`
studentGuy1
  • 浏览: 15455 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

多线程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 多线程 子线程 交替打印 奇偶数

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics