sleep的问题
军队作战到什么时候才会进行下一步Thread.sleep(50)呢
军队作战到什么时候才会进行下一步Thread.sleep(50)呢
2017-09-19
package com.junbao.thread; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadTest { static ExecutorService executorService = Executors . newFixedThreadPool (5) ; @SuppressWarnings("deprecation") public static void main(String[] args) throws InterruptedException { ThreadTest test = new ThreadTest(); List<Integer> numList = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) { numList.add(i); } // 队列 final BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(numList.size()); // 放入 try { for (Integer ints : numList) { queue.put(ints); } } catch (Exception e) { // TODO: handle exception } final List<Integer> outList = new ArrayList<Integer>(); for (int j = 0; j < 5; j++) { new Thread() { public void run() { while (true) { try { // 将此处的睡眠时间分别改为100和1000,观察运行结果 Thread.sleep((int) (Math.random() * (1000 - 100) + 100)); String name1 = Thread.currentThread().getName(); System.out.println(name1 + "准备取数据!"); Integer num = queue.take();// 如果没有了数据,就会阻塞 String name2 = Thread.currentThread().getName(); outList.add(num); System.out.println(name2 + "已经取走数据," + "队列目前有" + queue.size() + "个数据"); } catch (InterruptedException e) { e.printStackTrace(); } catch (NoSuchElementException e1) { // TODO: handle exception } } } }.start(); } try { while (true) { if (queue.isEmpty()) { System.out.println("空了,可以执行其他的任务了:打印输出转以后的列表"); test.showList(outList); System.out.println(Thread.currentThread().getState()); break; } } } catch (Exception e) { // TODO: handle exception } test(); } public void showList(List<Integer> list) { System.out.println(list.toString()); } public static void test(){ System.out.println("继续往下执行,看看还有什么可以做"); } }
举报