public class TwoThreadSynchronized {
private int start =1;
private boolean flag =false;
public static void main(String[] args) {
TwoThreadSynchronized twoThreadWaitNotify =new TwoThreadSynchronized();
Thread t1 =new Thread(new OuNum(twoThreadWaitNotify));
t1.setName("t1");
Thread t2 =new Thread(new JiNum(twoThreadWaitNotify));
t2.setName("t2");
t1.start();
t2.start();
}
public static class OuNumimplements Runnable {
TwoThreadSynchronizednumber;
public OuNum(TwoThreadSynchronized twoThreadWaitNotify) {
this.number = twoThreadWaitNotify;
}
@Override
public void run() {
while (number.start <=100) {
synchronized (TwoThreadSynchronized.class) {
System.out.println("偶数抢到锁了");
if (number.flag) {
System.out.println("number:" +number.start);
number.start++;
number.flag =true;
TwoThreadSynchronized.class.notify();
}else {
try {
TwoThreadSynchronized.class.wait();
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public static class JiNumimplements Runnable {
TwoThreadSynchronizednumber;
public JiNum(TwoThreadSynchronized number) {
this.number = number;
}
@Override
public void run() {
while (number.start <=100) {
synchronized (TwoThreadSynchronized.class) {
System.out.println("奇数抢到了");
if (!number.flag) {
System.out.println("number:" +number.start);
number.start++;
number.flag =true;
TwoThreadSynchronized.class.notify();
}else {
try {
TwoThreadSynchronized.class.wait();
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}