1.继承Thread
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | public class TestThread { public static void main(String[] args) { System.out.println( "程序.........启动了" ); //继承Thread Thread1 thread1= new Thread1(); thread1.start(); //启动继承Thread类型线程 System.out.println( "程序.........结束了" ); } //继承Thread public static class Thread1 extends Thread { @Override public void run() { System.out.println( "进入当前线程" ); System.out.println( "当前线程ID " + Thread.currentThread().getId()); System.out.println( "结束当前线程" ); } } } |
2.实现Runnable接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class TestThread { public static void main(String[] args) { System.out.println( "程序.........启动了" ); //实现Runnable接口 Runable1 runable1= new Runable1(); new Thread(runable1).start(); System.out.println( "程序.........结束了" ); } //实现Runnable接口 public static class Runable1 implements Runnable { @Override public void run() { System.out.println( "进入当前线程" ); System.out.println( "当前线程ID " + Thread.currentThread().getId()); System.out.println( "结束当前线程" ); } } } |
3.实现Callable接口+FutrueTask
callable方式不常用,但是相比于以上两种方式,可以拿到县城返回结果,可以处理异常。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | public class TestThreadPool { public static void main(String[] args) { List<String> totalList = new ArrayList<>(); ExecutorService service = Executors.newFixedThreadPool( 4 ); BlockingQueue<Future<List<String>>> queue = new LinkedBlockingDeque<>(); Future<List<String>> future1 = service.submit( new ExecuteTask()); Future<List<String>> future2 = service.submit( new ExecuteTask()); Future<List<String>> future3 = service.submit( new ExecuteTask()); Future<List<String>> future4 = service.submit( new ExecuteTask()); queue.add(future1); queue.add(future2); queue.add(future3); queue.add(future4); for ( int i= 0 ;i<queue.size();i++) { try { List<String> sqlList = queue.take().get(); totalList.addAll(sqlList); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } service.shutdown(); } } //这里的返回类型List<String>是自定义的,可以是任意类型 class ExecuteTask implements Callable<List<String>>{ public ExecuteTask(List<String> binList,List<String> locationList) { } public List<String> call() throws Exception{ List<String> sqlList = new ArrayList<String>(); return sqlList; } } |