1,繼承Thread類,重寫run方法;
public class Thread01 extends Thread{ public Thread01(){ } public void run(){ System.out.println(Thread.currentThread().getName()); } public static void main(String[] args){ Thread01 thread01 = new Thread01(); thread01.setName("繼承Thread類的線程1"); thread01.start(); System.out.println(Thread.currentThread().toString()); } }
2,實現Runnable接口,重寫run方法;
public class Thread02 { public static void main(String[] args){ System.out.println(Thread.currentThread().getName()); Thread t2 = new Thread(new MyThread02()); t2.start(); } } class MyThread02 implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName()+"2--實現Runnable接口的線程實現方式"); } }
3,實現Callable接口通過FutureTask包裝器來創建Thread線程;
4,通過線程池創建線程;
public class Thread04 { private static int POOL_NUM =10; public static void main(String[] args)throws InterruptedException { ExecutorService executorService = Executors.newFixedThreadPool(5); for (int i = 0; i < POOL_NUM; i++) { RunnableThread runnable =new RunnableThread (); executorService.execute(runnable); } executorService.shutdown(); } } class RunnableThread implements Runnable{ @Override public void run() { System.out.println("4--通過線程池創建的線程:" + Thread.currentThread().getName() + " "); } }
如果有幫助到您,望您打賞1元