public class A implements Runnable{
Demo demo;
public A(Demo demo){
this.demo=demo;
}
@Override
public void run() {
while(demo.getNum()<100){
demo.put();
}
}
}
public class B implements Runnable {
Demo demo;
public B(Demo demo){
this.demo=demo;
}
@Override
public void run() {
if(demo.getNum()<100){
demo.get();
}
}
}
public class Demo {
private int num=1;
/**
-
打印偶数
*/
public synchronized void put(){
if(num%2==0){
try {wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } notify(); System.out.println(Thread.currentThread().getName()+","+num); num++;
}
/**
-
打印奇数
*/
public synchronized void get(){
if(num%2!=0){
try {wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } notify(); System.out.println(Thread.currentThread().getName()+","+num); num++;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
public class Test {
public static void main(String[] args) {
Demo demo=new Demo();
A a=new A(demo);
B b=new B(demo);
Thread t1=new Thread(a);
Thread t2=new Thread(b);
t1.start();
t2.start();
}
}