Java线程创建的方式
继承Thread类
实现Runnable接口
通过ExecutorService和Callable
基于线程池
1、继承Thread类
使用便利,但Java是单继承,继承了Thread类就不能继承其它类了
publicclassThreadTestextendsThread{publicvoidrun(){System.out.println(currentThread().getName());}publicstaticvoidmain(String[]args){ThreadTestthread1=newThreadTest();ThreadTestthread2=newThreadTest();thread1.start();thread2.start();}}
2、实现Runnable接口
使用接口,避免了单继承的局限
publicclassThreadTestimplementsRunnable{@Overridepublicvoidrun(){System.out.println(Thread.currentThread().getName());}publicstaticvoidmain(String[]args){ThreadTestthreadTest=newThreadTest();Threadthread1=newThread(threadTest,"线程1");Threadthread2=newThread(threadTest,"线程2");thread1.start();thread2.start();}
3、使用FutureTask方法
以上两种创建方法都不带返回值,而用FutureTask方法创建线程,则有返回值
importjava.util.concurrent.Callable;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.FutureTask;publicclassThreadTestimplementsCallable<String>{@OverridepublicStringcall(){Stringname=Thread.currentThread().getName();returnname;}publicstaticvoidmain(String[]args)throwsExecutionException,InterruptedException{FutureTask<String>futureTask=newFutureTask<>(newThreadTest());Threadthread1=newThread(futureTask,"线程1");Threadthread2=newThread(futureTask,"线程2");thread1.start();thread2.start();System.out.println(futureTask.get());}}