package com.duia.statistic.common.achievement.data;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class test {
public static void main(String[] args) {
Test1 t1=new Test1();
t1.setName("张无忌");
Test1 t2=new Test1();
t2.setName("赵敏");
Test1 t3=new Test1();
t3.setName("韦一笑");
ExecutorService fixedThreadPool= Executors.newFixedThreadPool(3);
fixedThreadPool.execute(t1);
fixedThreadPool.execute(t2);
fixedThreadPool.execute(t3);
}
}
class Test1 implements Runnable {
private String name;
private static Integer num=10;
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
final private Object a=0;
@Override
public void run() {
while (true) {
synchronized (a){
if (num > 0) {//当剩余票大于0张时执行
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.getName() + "正在卖第" + num + "张票");
num--;
}
}
}
}
}
赵敏正在卖第10张票
韦一笑正在卖第9张票
韦一笑正在卖第8张票
韦一笑正在卖第7张票
张无忌正在卖第6张票
张无忌正在卖第5张票
韦一笑正在卖第4张票
韦一笑正在卖第3张票
韦一笑正在卖第2张票
韦一笑正在卖第1张票
新手注意的是实际应用中不要像我一样手动创建ExecutorService ,无边界的线程池默认值容易引起oom(挂了),应该去学习使用spring的
ThreadPoolTaskExecutor
为什么锁变量a而不用this,this会出现不安全,具体为什么我还没弄明白。
注意变量static



