synchronized--交替打印
public class TwoThreadSynchronized {
private intstart =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--交替打印】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();
}
}
}
}
}
}
推荐阅读
- Java|规范的打印日志
- Excel基础知识-打印的那些事(上)
- C/C++|C/C++ basis 02
- 用python实现PDF解密打印文件
- day8:作业
- 奥运的轮回,命运的交替
- 打印从1到最大的n位数
- RT-Thread|RT-Thread 入门学习笔记(vsnprintf来替代rt_vsnprintf来打印浮点)
- console.log无法打印
- 每日一练(9)(打印从1到最大的n位数)