线程依次交替执行解决办法

在面试题中,我们经常会遇到这样的题目,线程依次交替执行,比如有三个线程,第一个线程打印1-2-3,第二个线程接着打印4-5-6,第三个线程打印7-8-9,再更换到线程一运行打印10-11-12,依此类推。或者只有两个线程,他们直接交替执行。

我们知道,默认情况下,多线程运行,资源是共享的,也就是说他们是竞争关系,谁得到cpu资源,谁就运行,其他线程等待,当运行完毕,接下来由谁运行,是不确定的,有可能还是刚才抢占过cpu资源的线程执行。

按照一些面试题的要求,我们需要资源按顺序分配,或者公平分配,而不是去争抢。如果是两个线程,可以考虑使用公平锁,这个很好解决,看代码:

package com.xxx.lock;
import java.util.concurrent.locks.ReentrantLock;
public class FairLockDemo {

	public static void main(String[] args) {
		Runnable target = new Runnable(){
			private ReentrantLock lock = new ReentrantLock(true);
			@Override
			public void run() {
				int i=10;
				while (i>0) {
					try{
						lock.lock();
						System.out.println(Thread.currentThread().getName()+"get lock.for loop "+i);
					}finally{
						lock.unlock();
					}
					i--;
				}
			}		
		};
		
		Thread t1 = new Thread(target, "thread-1");
		Thread t2 = new Thread(target, "thread-2");
		t1.start();
		t2.start();
	}

}

运行结果:

thread-1 get lock.for loop 10
thread-2 get lock.for loop 10
thread-1 get lock.for loop 9
thread-2 get lock.for loop 9
thread-1 get lock.for loop 8
thread-2 get lock.for loop 8
thread-1 get lock.for loop 7
thread-2 get lock.for loop 7
thread-1 get lock.for loop 6
thread-2 get lock.for loop 6
thread-1 get lock.for loop 5
thread-2 get lock.for loop 5
t
### 实现三个线程顺序交替打印 #### Java 实现 在 Java 中,可以通过 `synchronized` 关键字和等待通知机制 (`wait()` 和 `notify()`) 来实现线程间的同步。以下是具体代码示例: ```java class PrintTask { private int current = 0; public synchronized void print(char c, int target) throws InterruptedException { while (current != target) { wait(); } System.out.print(c); current = (current + 1) % 3; notifyAll(); } } public class ThreadSyncExample { public static void main(String[] args) { final PrintTask task = new PrintTask(); Thread t1 = new Thread(() -> { try { for (int i = 0; i < 10; ++i) { task.print('A', 0); } } catch (InterruptedException e) {} }); Thread t2 = new Thread(() -> { try { for (int i = 0; i < 10; ++i) { task.print('B', 1); } } catch (InterruptedException e) {} }); Thread t3 = new Thread(() -> { try { for (int i = 0; i < 10; ++i) { task.print('C', 2); } } catch (InterruptedException e) {} }); t1.start(); t2.start(); t3.start(); } } ``` 上述代码中,通过共享变量 `current` 控制当前应该打印哪个字符,并使用 `wait()` 和 `notifyAll()` 方法协调线程之间的执行顺序[^4]。 --- #### C++ 实现 在 C++ 中,可以借助标准库中的 `<mutex>` 和 `<condition_variable>` 来实现类似的线程同步功能。以下是具体的代码示例: ```cpp #include <iostream> #include <thread> #include <mutex> #include <condition_variable> std::mutex mtx; std::condition_variable cv; int turn = 0; void printChar(const char ch, const int id) { for (int i = 0; i < 10; ++i) { std::unique_lock<std::mutex> lock(mtx); cv.wait(lock, [&]() { return turn == id; }); std::cout << ch; turn = (turn + 1) % 3; cv.notify_all(); } } int main() { std::thread t1(printChar, 'A', 0); std::thread t2(printChar, 'B', 1); std::thread t3(printChar, 'C', 2); t1.join(); t2.join(); t3.join(); return 0; } ``` 此代码片段展示了如何利用条件变量控制线程的运行顺序,从而达到交替打印的效果[^1]。 --- #### Python 实现 Python 的多线程支持主要依赖于 `threading` 模块。下面展示了一个基于锁和事件的解决方案: ```python import threading lock = threading.Lock() cv = threading.Condition(lock) turn = 0 def print_char(ch, idx): global turn for _ in range(10): with cv: cv.wait_for(lambda: turn == idx) print(ch, end='', flush=True) turn = (turn + 1) % 3 cv.notify_all() t1 = threading.Thread(target=print_char, args=('A', 0)) t2 = threading.Thread(target=print_char, args=('B', 1)) t3 = threading.Thread(target=print_char, args=('C', 2)) t1.start() t2.start() t3.start() t1.join() t2.join() t3.join() ``` 这段代码同样采用了条件变量来管理线程间的状态转换,确保每次只有一个线程被允许访问临界区并完成其任务[^2]。 --- ### 总结 以上三种语言都实现了三线程按照指定顺序依次打印字母 A、B 和 C 各十遍的任务。每种语言都有各自的特性用于解决此类问题,在实际开发过程中可以根据项目需求和个人偏好选择合适的工具和技术栈。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

luffy5459

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

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

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

打赏作者

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

抵扣说明:

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

余额充值