1 Runable实现
package com.zjapp.mythread.threadpool; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class TestMyThread{ public static void main(String[] args) { int threadnum = 6; ExecutorService service = Executors.newFixedThreadPool(1000);// 1 初始化 MyThread[] threads = new MyThread[threadnum]; for (int i = 0; i < threadnum; i++) { threads[i] = new MyThread(i+1); service.execute(threads[i]); // 调用 } service.shutdown();// 3 关闭 } } class MyThread implements Runnable{ private int threadnum; public MyThread(int threadnum) { this.threadnum = threadnum; } public void run() { for (int i = 1; i <= 5 ; i++) { System.out.printf("thread: %d: %d\n", threadnum, i); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } }
2 Callable实现
public class TestMyThread{ public static void main(String[] args) { int threadnum = 6; ExecutorService service = Executors.newFixedThreadPool(1000);// 1 初始化 MyThread[] threads = new MyThread[threadnum]; Future[] future = new Future[threadnum] ; for (int i = 0; i < threadnum; i++) { threads[i] = new MyThread(i+1); // service.execute(threads[i]); // 调用 //future[i] = service.submit(threads[i]); } for (Future f:future) { try { System.out.println(f.get()+" 结束了"); } catch (Exception e) { e.printStackTrace(); } } service.shutdown();// 3 关闭 } } class MyThread implements Callable<String> { private int threadnum; public MyThread(int threadnum) { this.threadnum = threadnum; } public String call() { for (int i = 1; i <= 5 ; i++) { System.out.printf("thread: %d: %d\n", threadnum, i); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } return "线程"+threadnum; } }
3 Runable接口和Callable在调用的的区别
Ranable(void run方法)-execute 而 Callable(String call方法)-submit