private ThreadPoolExecutor threadpool; private Runnable runnable; public HelloThread(){ threadpool=new ThreadPoolExecutor(2, 10, 10, TimeUnit.SECONDS, new ArrayBlockingQueue(10), new ThreadPoolExecutor.DiscardOldestPolicy()); threadpool.execute(new Runnable(){ public void run(){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }); } //add task into thread pool public void submit(final int flag){ runnable=new Runnable(){ public void run(){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(flag + " Hello"); } }; threadpool.execute(runnable); } /** * close thread pool */ public void shutdown() { threadpool.remove(runnable); threadpool.shutdown(); } @Test public void testThread(){ HelloThread t = new HelloThread(); for (int i = 0; i < 10; i++) { System.out.println("time:" + i); t.submit(i); } t.shutdown(); } public static void main(String[] args) { HelloThread t = new HelloThread(); for (int i = 0; i < 10; i++) { System.out.println("time:" + i); t.submit(i); } t.shutdown(); } 唯一不同是用main测试和testThread测试,输出的结果不同。
System.out.println(flag + " Hello"); 只有用main测试,才能输出 |