三个线程顺序执行

面试遇到这样一个问题:如果你有三个线程,分别为T1,T2,T3,如何让线程T2在线程T1之后执行,在线程T3之前执行。

public class Test {
	public static void main(String[] args) throws InterruptedException {
		final Thread t1 = new Thread(new Runnable(){
			@Override
			public void run() {
				try {
					Thread.sleep(5000);
					System.out.println(Thread.currentThread().getName());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		},"Thread-T1");
		final Thread t2 = new Thread(new Runnable(){
			@Override
			public void run() {
				try {
					t1.join();
					Thread.sleep(3000);
					System.out.println(Thread.currentThread().getName());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		},"Thread-T2");
		final Thread t3 = new Thread(new Runnable(){
			@Override
			public void run() {
				try {
					t2.join();
					Thread.sleep(1000);
					System.out.println(Thread.currentThread().getName());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		},"Thread-T3");
		t3.start();
		t2.start();
		t1.start();
	}
}
thread.Join把指定的线程加入到当前线程,可以将两个交替执行的线程合并为顺序执行的线程。比如在线程B中调用了线程A的Join()方法,直到线程A执行完毕后,才会继续执行线程B。
t.join();      //使调用线程 t 在此之前执行完毕。
t.join(1000);  //等待 t 线程,等待时间是1000毫秒


可以使用线程同步的方法来实现三个线程顺序执行,比如使用信号量或互斥锁。 具体实现方法如下: 1. 创建三个线程,分别执行任务 A、B、C。 2. 使用信号量或互斥锁来同步三个线程执行。在任务 A 执行完后,释放信号量或解锁互斥锁,使得任务 B 可以执行;在任务 B 执行完后,同样释放信号量或解锁互斥锁,使得任务 C 可以执行。 3. 在主线程中等待三个线程全部执行完毕,然后结束程序。 下面是一个简单的示例代码: ```c #include <stdio.h> #include <pthread.h> #include <semaphore.h> sem_t sem1, sem2; void *threadA(void *arg) { printf("Thread A\n"); sem_post(&sem1); // 释放信号量 sem1 pthread_exit(NULL); } void *threadB(void *arg) { sem_wait(&sem1); // 等待信号量 sem1 printf("Thread B\n"); sem_post(&sem2); // 释放信号量 sem2 pthread_exit(NULL); } void *threadC(void *arg) { sem_wait(&sem2); // 等待信号量 sem2 printf("Thread C\n"); pthread_exit(NULL); } int main() { sem_init(&sem1, 0, 0); // 初始化信号量 sem1 sem_init(&sem2, 0, 0); // 初始化信号量 sem2 pthread_t tid1, tid2, tid3; pthread_create(&tid1, NULL, threadA, NULL); pthread_create(&tid2, NULL, threadB, NULL); pthread_create(&tid3, NULL, threadC, NULL); pthread_join(tid1, NULL); pthread_join(tid2, NULL); pthread_join(tid3, NULL); sem_destroy(&sem1); // 销毁信号量 sem1 sem_destroy(&sem2); // 销毁信号量 sem2 return 0; } ``` 在上面的示例代码中,信号量 sem1 和 sem2 分别用来同步任务 A、B 和任务 B、C 的执行线程 A 执行完后释放信号量 sem1,线程 B 等待信号量 sem1,线程 B 执行完后释放信号量 sem2,线程 C 等待信号量 sem2。最后,主线程等待三个线程执行完毕后才结束程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fjkxyl

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值