Java 多线程 子线程 交替打印 奇偶数

本文介绍了一个使用Java实现的多线程程序案例,通过两个线程交替打印奇数和偶数,展示了如何利用synchronized关键字以及wait和notifyAll方法来控制线程间的同步与协作。

   Java 多线程 子线程 交替打印 奇偶数


public class Test{
	public static void main(String args[]){
		Num num = new Num(0);
		Thread thOdd = new Thread(new ThOdd(num));
		Thread thEdd = new Thread(new ThEdd(num));
		thOdd.setName("odd");
		thEdd.setName("edd");
		thOdd.start();
		thEdd.start();	
	}
}
class Num {
	public int num = 0;
	public Num(int num){
		this.num = num ;
	}
	public synchronized void printOdd(){
		System.out.println(Thread.currentThread().getName()+"------->"+(num++));
		try{
			this.notifyAll();
			this.wait();
			Thread.sleep(1000);
		}catch(Exception e){
			e.printStackTrace();		
		}
	}
	public synchronized void printEdd(){
		System.out.println(Thread.currentThread().getName()+(num++));
		try{
			this.notifyAll();
			this.wait();
			Thread.sleep(1000);
		}catch(Exception e){
			e.printStackTrace();	
		}
	}
}
class ThOdd implements Runnable{
	private Num num ;
	public ThOdd(Num num){
		this.num = num ;
	}	
	public void run(){
		while(true){
			num.printOdd();
		}
	}
} 
class ThEdd implements Runnable{
	private Num num ;
	public ThEdd(Num num){
		this.num = num ;
	}
	public void run(){
		while(true){
			num.printEdd();
		}
	}
}


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值