这段代码运行中会停止,有时候会报异常,把线程创建改成传统方式就没问题。可能是线程池的问题,但是不知道具体什么问题。求真相。
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- public class ThreadPoolTest {
-
- public static void main(String[] args) {
-
- ExecutorService es = Executors.newFixedThreadPool(3);
- Num n = new Num();
- while(n.get()>0){
- es.execute(n);
- }
-
- es.shutdown();
- }
- }
- class Num implements Runnable{
- private int ticket = 100;
-
- public int get(){
- return ticket;
- }
- Lock lock = new ReentrantLock();
-
- @Override
- public void run() {
- lock.lock();
- try {
- if(ticket>0){
- ticket--;
- Thread.sleep(50);
- System.out.println(Thread.currentThread().getName() + "卖掉" + (ticket+1) + "号票");
- }
-
- } catch (InterruptedException e) {
- e.printStackTrace();
- } finally {
- lock.unlock();
- }
-
- }
-
- }
复制代码 |
|