用俩个线程交替打奇数和偶数

1.要达到的效果:

奇数线程:1
偶数线程:2
奇数线程:3
偶数线程:4
奇数线程:5
偶数线程:6
奇数线程:7
偶数线程:8
奇数线程:9
偶数线程:10
奇数线程:11
偶数线程:12
奇数线程:13
偶数线程:14
奇数线程:15
偶数线程:16
奇数线程:17
偶数线程:18
奇数线程:19
偶数线程:20
奇数线程:21
偶数线程:22
奇数线程:23
偶数线程:24
奇数线程:25
偶数线程:26
奇数线程:27
偶数线程:28
奇数线程:29
偶数线程:30
奇数线程:31
偶数线程:32
奇数线程:33
偶数线程:34
奇数线程:35
偶数线程:36
奇数线程:37
偶数线程:38
奇数线程:39
偶数线程:40
奇数线程:41
偶数线程:42
奇数线程:43
偶数线程:44
奇数线程:45
偶数线程:46
奇数线程:47
偶数线程:48
奇数线程:49
偶数线程:50
奇数线程:51
偶数线程:52
奇数线程:53
偶数线程:54
奇数线程:55
偶数线程:56
奇数线程:57
偶数线程:58
奇数线程:59
偶数线程:60
奇数线程:61
偶数线程:62
奇数线程:63
偶数线程:64
奇数线程:65
偶数线程:66
奇数线程:67
偶数线程:68
奇数线程:69
偶数线程:70
奇数线程:71
偶数线程:72
奇数线程:73
偶数线程:74
奇数线程:75
偶数线程:76
奇数线程:77
偶数线程:78
奇数线程:79
偶数线程:80
奇数线程:81
偶数线程:82
奇数线程:83
偶数线程:84
奇数线程:85
偶数线程:86
奇数线程:87
偶数线程:88
奇数线程:89
偶数线程:90
奇数线程:91
偶数线程:92
奇数线程:93
偶数线程:94
奇数线程:95
偶数线程:96
奇数线程:97
偶数线程:98
奇数线程:99
偶数线程:100

代码:

package thread;

public class printNumDemo {
	static class Barrie{
		int number = 1;
		boolean isOdd = true;
		public Barrie() {}
	}
	/**
	 * 打印奇数
	 * @author Administrator
	 *
	 */
	static class OddPrint implements Runnable{
		Barrie barrie;
		public OddPrint() {}
		
		public OddPrint(Barrie barrie) {
			super();
			this.barrie = barrie;
		}

		@Override
		public void run() {
			synchronized(barrie) {
				while(barrie.number <= 100) {
					barrie.notify();
					if(barrie.isOdd) {
						System.out.println(Thread.currentThread().getName()+barrie.number);
						barrie.number ++;
						barrie.isOdd = false;
					}else {
						try {
							barrie.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
				
			}
		}
	}
	/**
	 * 打印偶数
	 * @author Administrator
	 *
	 */
	static class EvenPrint implements Runnable{
		Barrie barrie;
		public EvenPrint() {}
		
		public EvenPrint(Barrie barrie) {
			super();
			this.barrie = barrie;
		}

		@Override
		public void run() {
			synchronized(barrie) {
				while(barrie.number <= 100) {
					barrie.notify();
					if(!barrie.isOdd) {
						System.out.println(Thread.currentThread().getName()+barrie.number);
						barrie.number ++;
						barrie.isOdd = true;
					}else {
						try {
							barrie.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
				
			}
		}
	}
	public static void main(String[] args) {
		Barrie barrie = new Barrie();
		OddPrint oddPrint = new OddPrint(barrie);
		EvenPrint evenPrint = new EvenPrint(barrie);
		Thread t1 = new Thread(oddPrint);
		t1.setName("奇数线程:");
		Thread t2 = new Thread(evenPrint);
		t2.setName("偶数线程:");
		t1.start();
		t2.start();
		
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值