创建线程的4种方式
1、继承Thread类,复写run方法,run方法中为线程需要执行的逻辑部分,而启动线程调用start方法。小示例见代码,通过Thread.currentThread().getName()可以获得当前线程名称
1public class MyThread extends Thread { 2 private int i; 3 public void run(){ 4 for(;i<100;i++){ 5 System.out.println(Thread.currentThread().getName()+" "+i); 6 } 7 } 8}; 9 10 public static void main(String[] args) { 11 for(int i=0;i<100;i++){ 12 System.out.println(Thread.currentThread().getName()+""+i); 13 if(i==20){ 14 new MyThread().start(); 15 new MyThread().start(); 16 } 17 } 18 } 19
2、由于java不支持多继承,当需要继承另一个类时,与第一种方式冲突。于是可以使用第二种方法,通过实现Runnable接口。复写run方法。代码下
1public class MyThread2 implements Runnable{ 2 private int i; 3 @Override 4 public void run() { 5 for(;i<100;i++){ 6 System.out.println(Thread.currentThread().getName()+" "+i); 7 } 8 } 9} 10 public static void main(String[] args) { 11 for(int i=0;i<100;i++){ 12 System.out.println(Thread.currentThread().getName()+""+i); 13 if(i==20){ 14 MyThread2 myThread2 = new MyThread2(); 15 new Thread(myThread2).start(); 16 new Thread(myThread2).start(); 17 } 18 19 } 20
3使用callable和future,Callable()与Runable()不同的地方主要是,Callable方法有返回值。代码如下
1public class CallableDemo implements Callable<Integer> { 2 @Override 3 public Integer call() throws Exception { 4 int i = 5; 5 for(;i<100;i++){ 6 System.out.println(Thread.currentThread().getName()+" "+i); 7 } 8 return i; 9 } 10} 11 12 13 public static void main(String[] args) { 14 CallableDemo callableDemo = new CallableDemo(); 15 FutureTask<Integer> futureTask = new FutureTask<Integer>(callableDemo); 16 for(int i=0;i<100;i++){ 17 System.out.println(Thread.currentThread().getName()+""+i); 18 if(i==20){ 19 new Thread(futureTask,"有返回的线程:").start(); 20 try { 21 System.out.println("子线程的返回值" + futureTask.get()); 22 }catch(Exception e){ 23 e.printStackTrace(); 24 } 25 } 26 } 27 } 28
4、通过线程池创建线程,首先介绍几个相关的类:Executor,Executors,ExecutorService,Future。Executor为Java1.5后引入的一系列并发库中与executor相关的功能类。 Executors为一个创建线程的工厂,其中提供了4种创建线程的方式。 
<一>创建固定数量的线程。其中参数即为固定线程的数量。
1public static ExecutorService newFixedThreadPool(int nThreads) { 2 return new ThreadPoolExecutor(nThreads, nThreads, 3 0L, TimeUnit.MILLISECONDS, 4 new LinkedBlockingQueue<Runnable>()); 5 }
<二>创建可缓存的线程,线程超过60s会被回收。当缓存的没有线程可以使用时,则创建新线程使用。该情况下线程是无界的,只要想使用线程会无限的创建,除非发生内存溢出。
1public static ExecutorService newCachedThreadPool() { 2 return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 3 60L, TimeUnit.SECONDS, 4 new SynchronousQueue<Runnable>()); 5 }
<三>创建一个单线程化的Executor。
1public static ExecutorService newSingleThreadExecutor() { 2 return new FinalizableDelegatedExecutorService 3 (new ThreadPoolExecutor(1, 1, 4 0L, TimeUnit.MILLISECONDS, 5 new LinkedBlockingQueue<Runnable>())); 6 } 7
<四>创建一个支持定时及周期性的任务执行的线程池,多数情况下可用来替代Timer类。
1 public static ScheduledExecutorService newScheduledThreadPool( 2 int corePoolSize, ThreadFactory threadFactory) { 3 return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory); 4 }