创建线程
-
继承Thread类创建线程
public class MyThread extends Thread { @Override public void run() { System.out.println("线程正在运行"); try { Thread.sleep(1000); // 模拟线程工作 } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) { MyThread myThread = new MyThread(); Thread thread1 = new Thread(myThread); Thread thread2 = new Thread(myThread); thread1.start(); // 启动线程 thread2.start(); // 启动线程 } } -
实现Runnable接口创建线程
public class MyRunnable implements Runnable{ @Override public void run(){ System.out.println("线程正在运行"); } public static void main(String[] args) { MyRunnable myRunnable = new MyRunnable(); Thread thread1 = new Thread(myRunnable); Thread thread2 = new Thread(myRunnable); thread1.start(); // 启动线程 thread2.start(); // 启动线程 } } -
实现Callable类创建线程
import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; public class MyCallable implements Callable<String> { @Override public String call() throws Exception{ System.out.println("线程正在运行"); return "线程执行完毕"; } public static void main(String[] args) throws ExecutionException, InterruptedException { MyCallable mc = new MyCallable(); FutureTask<String> futureTask = new FutureTask<>(mc); Thread thread1 = new Thread(futureTask); Thread thread2 = new Thread(futureTask); thread1.start(); // 启动线程1 thread2.start(); // 启动线程2 String result = futureTask.get();// 等待线程1执行完毕并获取结果 System.out.println(result); } }输出如下
线程正在运行 线程执行完毕 进程已结束,退出代码为 0有个疑问,为什么这个线程2启动后没有输出
原因是:FutureTask 只能被执行一次。你创建了两个线程(thread1 和 thread2),但它们都传入了同一个 FutureTask 实例。第一个线程启动后,FutureTask 的任务就开始执行了,第二个线程再启动时,发现任务已经被执行过了,所以不会再执行 call() 方法,也不会输出相关内容。
FutureTask再创建一个实例放到线程2中,就能输出了。
import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; public class MyCallable implements Callable<String> { @Override public String call() throws Exception{ System.out.println("线程正在运行"); return "线程执行完毕"; } public static void main(String[] args) throws ExecutionException, InterruptedException { MyCallable mc = new MyCallable(); FutureTask<String> futureTask = new FutureTask<>(mc); FutureTask<String> futureTask2 = new FutureTask<>(mc); Thread thread1 = new Thread(futureTask); Thread thread2 = new Thread(futureTask2); thread1.start(); // 启动线程1 thread2.start(); // 启动线程2 String result = futureTask.get();// 等待线程1执行完毕并获取结果 System.out.println(result); } } -------------------------------- 线程正在运行 线程正在运行 线程执行完毕 进程已结束,退出代码为 0 -
使用线程池创建线程
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class MyExecutors implements Runnable{ @Override public void run(){ System.out.println("线程正在运行"); } public static void main(String[] args) { ExecutorService threadPool = Executors.newFixedThreadPool(3); threadPool.submit(new MyExecutors()); threadPool.shutdown(); } }
面试问题
创建线程的四种方式
在java中一共有四种常见的创建方式,分别是:继承Thread类、实现runnable接口、实现Callable接口、线程池创建线程。通常情况下,我们项目中都会采用线程池的方式创建线程。