這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)?lái)有關(guān)怎么在Java項(xiàng)目中創(chuàng)建一個(gè)多線程,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
java有以下四種創(chuàng)建多線程的方式
1:繼承Thread類創(chuàng)建線程
2:實(shí)現(xiàn)Runnable接口創(chuàng)建線程
3:使用Callable和FutureTask創(chuàng)建線程
4:使用線程池,例如用Executor框架創(chuàng)建線程
DEMO代碼
package thread; import java.util.concurrent.*; public class ThreadTest { public static void main(String[] args) throws ExecutionException, InterruptedException { // 創(chuàng)建線程的第一種方法 Thread1 thread1 = new Thread1(); thread1.start(); // 創(chuàng)建線程的第二種方法 Thread2 thread2 = new Thread2(); Thread thread = new Thread(thread2); thread.start(); // 創(chuàng)建線程的第三種方法 Callablecallable = new Thread3(); FutureTask futureTask = new FutureTask<>(callable); Thread thread3 = new Thread(futureTask); thread3.start(); String s = futureTask.get(); System.out.println(s); // 創(chuàng)建線程的第四種方法 Executor executor = Executors.newFixedThreadPool(5); executor.execute(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread()+"創(chuàng)建線程的第四種方法"); } }); ((ExecutorService) executor).shutdown(); } } class Thread1 extends Thread{ @Override public void run() { System.out.println(Thread.currentThread()+"創(chuàng)建線程的第一種方法"); } } class Thread2 implements Runnable { @Override public void run() { System.out.println(Thread.currentThread()+"創(chuàng)建線程的第二種方法"); } } class Thread3 implements Callable { @Override public String call() throws Exception { return Thread.currentThread()+"創(chuàng)建線程的第三種方法"; } }