使用wait(),两个线程交替执行

本文提供了两种使用Java实现线程同步的方法。方法一通过一个包含标志位和等待通知机制的自定义类来协调两个线程的交替打印操作;方法二则直接利用对象锁进行线程间的同步,代码更为简洁明了。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法1:忘记从哪看的了,设计得比较繁琐。

class Num{

	int i = 1;

	boolean flag = false;

}

public class TestXX {

	public static void main(String[] args) {
		Num num = new Num();

		new Thread(new Runnable() {

			@Override
			public void run() {
				for(int i=0;i<10;i++) {
					synchronized (num) {
						if(!num.flag) { //false 进入
							try {
								num.wait();
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}else {
							System.out.println(Thread.currentThread().getName()+"   "+num.i);
							num.i ++;
							num.flag = false;
							num.notify();
						}
					}
				}

			}
		}).start();


		new Thread(new Runnable() {

			@Override
			public void run() {
				for(int i=0;i<10;i++) {
					synchronized (num) {
						if(num.flag) { //true进入
							try {
								num.wait();
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}else {
							System.out.println(Thread.currentThread().getName()+"   "+num.i);
							num.i ++;
							num.flag = true;
							num.notify();
						}
					}
				}
			}
		}).start();


	}

}

方法2:原文:https://www.cnblogs.com/stateis0/p/9091254.html。我稍作修改,其形式较为简单:

public class testXXX {

	public static void main(String[] args) {		
		Object obj = new Object();	

		new Thread(new Runnable() {
			@Override
			public void run() {		
				for(int i=0;i<10;i++) {
					synchronized (obj) {		
						System.out.println(Thread.currentThread().getName()+"  "+i);
						obj.notify();
						
						if(i==9) {
							break;
						}
						try {
							obj.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}	
			}
		}).start();


		new Thread(new Runnable() {
			@Override
			public void run() {		
				for(int i=0;i<10;i++) {
					synchronized (obj) {		
						System.out.println(Thread.currentThread().getName()+"  "+i);

						obj.notify();
						if(i==9) {
							break;
						}
						try {
							obj.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}

					}
				}	
			}
		}).start();

	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值