1.继承Thread类,重写run方法; 2.实现Runnable接口,重写run方法; 3.实现Callable接口,重写call方法; 4.通过线程池实现多线程(实现Runnable接口+Executors创建线程池);
前2种方法无返回值,后2种方法有返回值。
继承Thread类,重写run方法
public class TTEST extends Thread{ @Override public void run() { System.out.println(Thread.currentThread().getName()); } public static void main(String[] args) { Thread t1 = new TTEST(); Thread t2 = new TTEST(); t1.setName("线程1"); t2.setName("线程2"); t1.start(); t2.start(); }
实现Runnable接口,重写run方法
public class RunnableThread implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName()); } public static void main(String[] args) { System.out.println(Thread.currentThread().getName()); RunnableThread runnableThread = new RunnableThread(); Thread t1 = new Thread(runnableThread); t1.setName("线程1"); t1.start(); } }
实现Callable接口,重写call方法
因为FutureTask类实现了RunnaleFuture,而RunnaleFuture又实现了Runnable接口和Future接口,通过FutureTask封装继承Callable接口的类
import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; public class CollableThread implements Callable<Object>{ @Override public Object call() throws Exception { System.out.println(Thread.currentThread().getName()); return null; } public static void main(String[] args) { System.out.println(Thread.currentThread().getName()); CollableThread collableThread = new CollableThread(); FutureTask<Object> futureTask = new FutureTask<Object>(collableThread); Thread t1 = new Thread(futureTask); t1.setName("线程1"); t1.start(); } }
通过线程池实现多线程(实现Runnable接口+Executors创建线程池)
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class PoolThread implements Runnable{ private static int POOL_NUM = 10;//线程池数量 @Override public void run() { System.out.println(Thread.currentThread().getName()); } public static void main(String[] args) { ExecutorService threadPool = Executors.newFixedThreadPool(5); for (int i = 0; i < POOL_NUM; i++) { PoolThread poolThread = new PoolThread(); threadPool.execute(poolThread); } threadPool.shutdown();//关闭线程池 } }