题目
使用三个线程按顺序精准控制输出“关山口”、“男子”、“职业技术学院”。
解决思路
还是先放上之前的一个图,原理就是各个线程之间等待唤醒、等待唤醒... ...
开撸代码
Java可以在主线程里创建三个子线程,通过原子整数num控制各个线程是继续等待还是被唤醒。
package com.hust.zhang.concurrent;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class OrderControl {
//定义循环次数
private static final int count = 10;
//定义一个原子整数
private static AtomicInteger num = new AtomicInteger(0);
//定义一个可重入锁
private static Lock lock = new ReentrantLock();
//Condition替代传统的Object的wait()、notify()实现线程间的协作
private static Condition condition = lock.newCondition();
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
lock.lock();
try {
for (int i = 0; i < count; i++) {
while (num.get() == 1 || num.get() == 2) {
condition.await();
}
System.out.print("关山口");
num.incrementAndGet();
condition.signalAll();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
});
Thread t2 = new Thread(() -> {
lock.lock();
try {
for (int i = 0; i < count; i++) {
while (num.get() == 0 || num.get() == 2) {
condition.await();
}
System.out.print("男子");
num.incrementAndGet();
condition.signalAll();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
});
Thread t3 = new Thread(() -> {
lock.lock();
try {
for (int i = 0; i < count; i++) {
while (num.get() == 0 || num.get() == 1) {
condition.await();
}
System.out.println("职业技术学院");
num.set(0);
condition.signalAll();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
});
t1.start();
t2.start();
t3.start();
}
}
Go语言中可以通过通道去控制各个协程(Goroutine)之间的执行顺序,如下,
package main
import(
"fmt"
"sync"
"sync/atomic"
)
const num = 10
var(
wg sync.WaitGroup
str1Count uint64
str2Count uint64
str3Count uint64
)
func main(){
str1Ch := make(chan struct{}, 1)
str2Ch := make(chan struct{}, 1)
str3Ch := make(chan struct{}, 1)
wg.Add(3)
go str1(&wg, str1Count, str1Ch, str2Ch)
go str2(&wg, str2Count, str2Ch, str3Ch)
go str3(&wg, str3Count, str3Ch, str1Ch)
str1Ch <- struct{}{}
wg.Wait()
}
//内建函数make返回的就是指针,所以传参时chan本身就是指针类型,而sync.WaitGroup是type类型,需要通过指针来传递值
func str1(wg *sync.WaitGroup,count uint64,source chan struct{}, destination chan struct{}){
for{
if count>uint64(num){
wg.Done()
return
}
<-source
fmt.Print("关山口")
atomic.AddUint64(&count, 1)
destination<-struct{}{}
}
}
func str2(wg *sync.WaitGroup,count uint64,source chan struct{}, destination chan struct{}){
for{
if count>uint64(num){
wg.Done()
return
}
<-source
fmt.Print("男子")
atomic.AddUint64(&count, 1)
destination<-struct{}{}
}
}
func str3(wg *sync.WaitGroup,count uint64,source chan struct{}, destination chan struct{}){
for{
if count>uint64(num){
wg.Done()
return
}
<-source
fmt.Println("职业技术学院")
atomic.AddUint64(&count, 1)
destination<-struct{}{}
}
}
总结
上面两种写法都可以达到相同的效果,然而去实现这种功能绝不仅仅只能这样去写,大家可以多多尝试,这只是一个简单的思路。