while (true) { synchronized (queue) { while (queue.isEmpty()) { try { queue.wait(); // 线程没有任务,进入睡眠 } catch (InterruptedException e) { System.out.println("An error occurred while queue is waiting: " + e.getMessage()); } } // 线程被唤醒之后,会顺利执行到这里 task = queue.poll(); // 获取任务 }
// If we don't catch RuntimeException, // the pool could leak threads try { task.run(); // 执行任务 } catch (RuntimeException e) { System.out.println("Thread pool is interrupted due to an issue: " + e.getMessage()); } } } } }
为了控制线程对工作队列的访问,一定要给工作队列加上同步锁。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
package tutorials;
publicclassTaskimplementsRunnable {
privateint num;
publicTask(int n) { num = n; }
publicvoidrun() { System.out.println("Task " + num + " is running."); } }