import lombok.Data;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@Data
public class Game2 {
private String str;
private boolean end;
private Lock lock = new ReentrantLock();
Condition t1 = lock.newCondition();
Condition t2 = lock.newCondition();
public static void main(String[] args) {
Game2 game2 = new Game2();
new Thread(game2::input, "t1").start();
game2.output();
}
public void input() {
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in))){
while (!end) {
lock.lock();
try {
while (getStr() != null) {
t1.await();
}
System.out.println("please input a line");
setStr(bufferedReader.readLine());
if ("exit".equals(getStr())) {
end = true;
}
t2.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void output() {
while (!end) {
lock.lock();
try {
while (getStr() == null) {
t2.await();
}
System.out.println(getStr());
setStr(null);
t1.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
JUC_一个线程输入字符串,主线程输出字符串,“exit”表示退出,否则持续交互
最新推荐文章于 2022-11-07 09:59:59 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)