一、有两个线程交替进行,操作一个数字,一个对数字加1,一个对数字减1.
public class TestThread111 {
private static int n=8;
private static int state = 1;
public static void main(String[] args) {
final TestThread111 pn =new TestThread111();
new Thread(new Runnable(){
public void run(){
for(int i=0;i<20;i++){
synchronized (pn) {
while (state != 1)
try {
pn.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"...:"+ ++n);
state =2;
pn.notifyAll();
}
}
}
}).start();
new Thread(new Runnable(){
public void run(){
for(int i=0;i<20;i++){
synchronized (pn) {
while (state != 2)
try {
pn.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"...:"+ --n);
state = 1;
pn.notifyAll();
}
}
}
}).start();
}
}