加锁版
利用锁保证线程同步,多个线程共享同一变量threadId,每次打印完之后,就将threadId修改为自己的下一任线程可以拿到锁的状态。
C++
#include <mutex>
#include <thread>
#include <condition_variable>
using namespace std;
mutex m; //全局锁
condition_variable cv;//条件变量
int id=1;//标记那个线程拥有打印权限
void print(int curId,int nextId,string letter){
unique_lock<mutex>lock(m);
for (int i = 0; i < 10; ++i) {
while (curId!=id){ //如果我没有权限那就阻塞等待
cv.wait(lock);
}
//有权限了打印
cout<<letter;
id=nextId; //将权限赋给下一任
cv.notify_all();//唤醒所有阻塞等待的线程
}
}
int main() {
thread t1(print,1,2,"A");
thread t2(print,2,3,"B");
thread t3(print,3,1,"C");
t1.join();
t2.join();
t3.join();
return 0;
}
java
class Resource {
private int loop; //打印次数
private int threadId;//标记那个线程拥有打印权限
public Resource(int loop, int threadId) {
this.loop = loop;
this.threadId = threadId;//初始拥有打印权限的线程id
}
public void print(int curThreadId, int nextThreadId, String letter) {
for (int i = 0; i < loop; i++) {//循环loop次
synchronized (this) { //拿对象锁
while (this.threadId != curThreadId) { //没有轮到自己就释放锁等待
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "打印 " + letter); //打印ABCABC....
this.threadId = nextThreadId; //设置下一个线程可以打印
notifyAll(); //唤醒所有其他线程
}
}
}
}
class Solution {
public static void main(String[] args) {
Resource res = new Resource(10, 1);
new Thread(()->res.print(1,2,"A")).start();
new Thread(()->res.print(2,3,"B")).start();
new Thread(()->res.print(3,1,"C")).start();
}
}
不加锁版
不加锁的话,就是利用线程之间的通信原理了,多个线程修改同一个变量并告知其他线程,然后利用取模来决定由谁打印
java
class Resource{
private int cnt=0;
public void print(int num,String letter){
int i=0;
while (i<10){
if(cnt%3==num){
System.out.println(Thread.currentThread().getName()+"打印:"+letter);
cnt++;
i++;
}
}
}
}
class t{
public static void main(String[] args) {
Resource res = new Resource();
new Thread(()->res.print(0,"A"),"a").start();
new Thread(()->res.print(1,"B"),"b").start();
new Thread(()->res.print(2,"C"),"c").start();
}
}
c++
int cnt=0;
void print1(int num,string letter){
int i=0;
while (i<10){
if(cnt%3==num){
cout<<letter;
cnt++;
i++;
}
}
}
int main() {
thread t1(print1,0,"A");
thread t2(print1,1,"B");
thread t3(print1,2,"C");
t1.join();
t2.join();
t3.join();
return 0;
}