如何让多线程按顺序执行

方法一:在子线程中通过join()方法指定顺序

通过join()方法使当前线程“阻塞”,等待指定线程执行完毕后继续执行,比如在线程thread2中,加上一句thread1.join(),其意义在于,当前线程2运行到此行代码时会进入阻塞状态,直到线程thread1执行完毕后,线程thread2才会继续运行,这就保证了线程thread1与线程thread2的运行顺序

方法二:在主线程中通过join()方法指定顺序

上面我们是在子线程中指定join()方法,我们还可以在主线程中通过join()方法让主线程阻塞等待以达到指定顺序执行的目的

方法三:使用Object的wait和notifyAll方法

package printABC.method1;
 
//第一种方法,使用Object的wait和notifyAll方法
public class TestPrint {
	static int count = 0;
	static final Object obj = new Object();
	Thread t1 = new Thread(new Runnable() {
		@Override
		public void run() {
			while (true) {
				synchronized (obj) {
					if (count % 3 == 0) {
						System.out.println("A");
						count++;
						obj.notifyAll();
					} else
						try {
							obj.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
				}
			}
		}
	});
	Thread t2 = new Thread(new Runnable() {
		@Override
		public void run() {
			while (true) {
				synchronized (obj) {
					if (count % 3 == 1) {
						System.out.println("B");
						count++;
						obj.notifyAll();
					} else
						try {
							obj.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
				}
			}
		}
	});
	Thread t3 = new Thread(new Runnable() {
		@Override
		public void run() {
			while (true) {
				synchronized (obj) {
					if (count % 3 == 2) {
						System.out.println("C");
						count++;
						obj.notifyAll();
					} else
						try {
							obj.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
				}
			}
		}
	});
 
	public void fun() {
		t3.start();
		t1.start();
		t2.start();
	}
 
	public static void main(String[] args) {
		TestPrint tp = new TestPrint();
		long t1 = System.currentTimeMillis();
		tp.fun();
		while (true) {
			if (System.currentTimeMillis() - t1 >= 10)// 运行10个毫秒
				System.exit(0);
		}
	}
}

一种方式可以通过求余方法来判断到哪个线程执行,当执行完该线程之后,再使用notifyAll()方法来唤醒线程,让后面的线程继续执行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值