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();
}
}
B class 写的是 if
public class PrintNumber {
private int iterator;
private int limit;
private int start;
public PrintNumber(int limit,int start) {
this.limit=limit;
this.iterator=start;
this.start=start;
}
public synchronized void printSingle() {
//如果是偶数的话则wait
while ((iterator % 2) == 0 && iterator<=limit && start%2==0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
while ((iterator % 2) != 0 && iterator<=limit) {
System.out.println(Thread.currentThread().getName() + "---" + iterator++);
notify();//唤醒打印偶数
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
notify();
}
public synchronized void printDouble() {
//如果是奇数的话 则wait
while ((iterator % 2) != 0 && iterator<=limit && start%2!=0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
while ((iterator % 2) == 0 && iterator<=limit) {
System.out.println(Thread.currentThread().getName() + "---" + iterator++);
notify();//唤醒打印奇数
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
notify();
}
}