我只是想使用线程打印从1到10。但是我的代码将在数字1处停止。input()将提供从1到10的变量,而output()将打印出它们。首先执行input(),然后执行output()。之后 for() 将确保它们将开始另一个迭代。
class InputOutput{
private static int i=0;
private static boolean ToF=false;
synchronized void output(){
try{
while(!ToF){
notify();
wait();
}
}
catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("Output: "+i);
ToF=false;
notify();
}
synchronized void input(){
try{
while(ToF){
notify();
wait();
}
}
catch(InterruptedException e){
e.printStackTrace();
}
i++;
ToF=true;
notify();
}
class input implements Runnable{
private int i=1;
InputOutput io=new InputOutput();
public void run(){
for(i=1;i<=10;i++)
io.input();
}
}
class output implements Runnable{
private int i=1;
InputOutput io=new InputOutput();
public void run(){
for(i=1;i<=10;i++)
io.output();
}
}
public class Homework07Part3 {
public static void main(String[] args) {
Thread t1=new Thread(new input());
t1.start();
Thread t2=new Thread(new output());
t2.start();
}
}
最佳答案
while 循环将等待两个线程通信的单个对象
while(ToF){
//dont put notify here.
notify();
wait();
}
使其成为实例变量
private static boolean ToF=false;
公共(public)课Homework07Part3{
public static void main(String[] args) {
InputOutput io = new InputOutput();
Thread t1 = new Thread(new input(io));
t1.start();
Thread t2 = new Thread(new output(io));
t2.start();
}
private static class input implements Runnable {
private int i = 1;
private InputOutput io;
public input(InputOutput io) {
this.io = io;
}
public void run() {
for (i = 1; i <= 10; i++)
io.input();
}
}
private static class output implements Runnable {
private int i = 1;
private InputOutput io;
public output(InputOutput io) {
this.io = io;
}
public void run() {
for (i = 1; i <= 10; i++)
io.output();
}
}
}
class InputOutput {
private int i = 0;
private boolean ToF = false;
synchronized void output() {
try {
while (!ToF) {
wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Output: " + i);
ToF = false;
notify();
}
synchronized void input() {
try {
while (ToF) {
wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
ToF = true;
notify();
}
}
关于java - wait() 和 notification() 相关问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44114205/