编写一个应用程序,除了主线程外,还有两个子线程。两个子线程对同一个数据操作,其中一个线程负责对该数据做递增操作,一个线程负责对该线程做递减操作。当这个数据小于0的话,递减操作等待,当这个数据大于100

来源:互联网 发布:中国债务危机 知乎 编辑:程序博客网 时间:2024/06/06 03:45

编写一个应用程序,除了主线程外,还有两个子线程。两个子线程对同一个数据操作,其中一个线程负责对该数据做递增操作,一个线程负责对该线程做递减操作。当这个数据小于0的话,递减操作等待,当这个数据大于100的话,递增操作等待。这道题就是一个线程常见的问题。

public class Demo{
public static void main(String[] args){
Number nb = new Number(0);
Runner1 r1 = new Runner1(nb);
Runner2 r2 = new Runner2(nb);
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
}


class Number{
int i;
Number(int i){
this.i = i;
}
}


class Runner1 implements Runnable{


Number n = null;
Runner1(Number n){
this.n = n;
}
public void run(){
System.out.println("递减");
synchronized(n){
while(n.i < 100){
if(n.i <= 0){
try{
n.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}

System.out.println("数  字"+n.i);
n.i--;
n.notify();
}
}
}
}




class Runner2 implements Runnable{
Number n = null;
Runner2(Number n){
this.n = n;
}
public void run(){
System.out.println("递增");
synchronized(n)
{
while(n.i >= 0){
if(n.i >= 100){
try{
n.wait();
}catch(InterruptedException e){
e.printStackTrace();


}
}
System.out.println("数字"+n.i);
n.i++;
n.notify();
}
}


}
}


运行会死循环,终止掉答案是对的。其中注意的是wait()。是n.wait()不能用this.wait();

0 0
原创粉丝点击