编写一个应用程序,除了主线程外,还有两个子线程。两个子线程对同一个数据操作,其中一个线程负责对该数据做递增操作,一个线程负责对该线程做递减操作。当这个数据小于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();
本文介绍了一个使用Java实现的线程同步示例,其中包括两个线程对同一数据进行递增和递减操作,并通过synchronized关键字及wait和notify方法确保线程间的正确同步。

960

被折叠的 条评论
为什么被折叠?



