package DUOXIAN;
import java.util.concurrent.TimeUnit;
public class Sync {
public static void main(String[] args) {
MySync ms =new MySync();
new Thread(()->{
while (true){
if (ms.getNum()>0){
ms.add();
}else {
break;
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"t1").start();
new Thread(()->{
while (true){
if (ms.getNum()>0){
ms.add();
}else {
break;
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"t2").start();
new Thread(()->{
while (true){
if (ms.getNum()>0){
ms.add();
}else {
break;
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"t3").start();
}
}
class MySync{
private int num=100;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public synchronized void add(){//不加锁可能会出现脏读
//2%线程名,$1数量
System.out.printf("%2$s:add..%1$d%n",num--,Thread.currentThread().getName());
}
}