Java 指定A B C 三个线程顺序执行

多个线程顺序执行

日常总结都在github,大家可以看一下: https://github.com/nocoders/java-everything.git,本文示例代码在src.main.test.com.javaEverything.java.concurrent目录下

今天面试遇到这个问题,A、B、C三个线程,如何让他们按照顺序执行。当时没想起来怎么说,后来百度了下,发现实现有好几种方式,可以使用Thread.join()、使用ReentrantLock、使用Semaphore

Thread.join()

Thread.join():阻塞当前线程,直到执行线程执行结束。

定义三个线程,A线程直接start,B线程要等A线程执行结束才能执行,C线程要等A B线程执行结束才能执行。

示例代码

@Test
public void threadSortJoin() {
	Thread A = new Thread(() -> {
		System.out.println("Thread A run");
	});
	Thread B = new Thread(() -> {
		try {
			A.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		System.out.println("Thread B run");
	});
	Thread C = new Thread(() -> {
		try {
			A.join();
			B.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("Thread C run");
	});

	A.start();
	B.start();
	C.start();
}

Semaphore

Semaphore相关见参考链接2,给线程B、C定义两个信号量为0的Semaphore,A线程中执行完毕释放B线程对应的信号量,B线程执行完毕释放C线程的信号量。

示例代码

@Test
public void threadSortSemaphore() {
	 Semaphore sb = new Semaphore(0);
	 Semaphore sc = new Semaphore(0);
	 Thread A = new Thread(()->{
		 System.out.println("Thread A run");
		 sb.release();
	 });
	 Thread B = new Thread(()->{
		 try {
			 sb.acquire();
		 } catch (InterruptedException e) {
			 e.printStackTrace();
		 }
		 System.out.println("Thread B run");
		 sc.release();
	 });
	Thread C = new Thread(() -> {
		try {
			sc.acquire();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("Thread C run");
	});
	A.start();
	B.start();
	C.start();
}

ReentrantLock

定义一个number指定线程执行顺序,定义三个condition,number等于几,唤醒第几个线程执行。

@Test
	public void threadSortReentrantLock() {
		ReentrantLock lock = new ReentrantLock();
		Condition conditionA = lock.newCondition();
		Condition conditionB = lock.newCondition();
		Condition conditionC = lock.newCondition();
		AtomicInteger number = new AtomicInteger(1);
		Thread A = new Thread(() -> {
			System.out.println(1);
			lock.lock();
			try {
				while (number.get() != 1) {
					conditionA.await();
				}
				System.out.println("Thread A run");
				number.set(2);
				conditionB.signal();

			} catch (Exception e) {
			} finally {
				lock.unlock();
			}
		});
		Thread B = new Thread(() -> {
			System.out.println(2);
			lock.lock();
			try {
				while (number.get() != 2) {
					conditionB.await();
				}
				System.out.println("Thread B run");
				number.set(3);
				conditionC.signal();

			} catch (Exception e) {
			} finally {
				lock.unlock();
			}
		});
		Thread C = new Thread(() -> {
			System.out.println(3);
			while (number.get()!=2){
				
			}
			lock.lock();
			try {
				while (number.get() != 3) {
					conditionC.await();
				}
				System.out.println("Thread C run");
				number.set(1);
				conditionA.signal();

			} catch (Exception e) {
			}finally {
				lock.unlock();
			}
		});
		
		A.start();
		B.start();
		C.start();
	}

参考链接

  1. 多线程中Thread的join方法
  2. Semaphore 使用及原理
  3. JAVA实现多个线程顺序执行的几种方式
  4. [让线程按顺序执行8种方法](
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用线程的 wait() 和 notify() 方法来实现按顺序打印ABC的需求。具体实现如下: ```java public class PrintABC { private int times; // 打印次数 private int state; // 当前状态:0-A,1-B,2-C public PrintABC(int times) { this.times = times; this.state = 0; } public synchronized void printA() throws InterruptedException { for (int i = 0; i < times; i++) { while (state != 0) { wait(); } System.out.print("A"); state = 1; notifyAll(); } } public synchronized void printB() throws InterruptedException { for (int i = 0; i < times; i++) { while (state != 1) { wait(); } System.out.print("B"); state = 2; notifyAll(); } } public synchronized void printC() throws InterruptedException { for (int i = 0; i < times; i++) { while (state != 2) { wait(); } System.out.print("C"); state = 0; notifyAll(); } } } ``` 在主函数中创建三个线程,分别调用 PrintABC 类中的 printA()、printB() 和 printC() 方法: ```java public static void main(String[] args) { PrintABC printABC = new PrintABC(10); Thread threadA = new Thread(() -> { try { printABC.printA(); } catch (InterruptedException e) { e.printStackTrace(); } }); Thread threadB = new Thread(() -> { try { printABC.printB(); } catch (InterruptedException e) { e.printStackTrace(); } }); Thread threadC = new Thread(() -> { try { printABC.printC(); } catch (InterruptedException e) { e.printStackTrace(); } }); threadA.start(); threadB.start(); threadC.start(); } ``` 执行结果: ```java ABCABCABCABCABCABCABCABCABCABC ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值