线程的三种实现方法:
(1)继承 Thread 类,重写run()方法;
(2)实现 Runnable 接口,重写run() 方法;
(3)实现 Callable 接口,重写call()方法;
方式一: 继承Thread类
public class MyThreadDemo { public static void main(String[] args) { Thread thread = new MyThread(); thread.start(); } } class MyThread extends Thread { @Override public void run() { System.out.println("extends Thread"); } }
方式二: 实现 Runnable 接口
public class MyRunnableDemo { public static void main(String[] args) { //方法一 Thread thread = new Thread(new MyRunnable()); thread.start(); //启动线程 //方法二 匿名类 Thread thread1 = new Thread(new Runnable() { @Override public void run() { System.out.println("anonymous class implement Runnable"); } }); thread1.start(); //启动线程 } } class MyRunnable implements Runnable { @Override public void run() { System.out.println("implement Runnable"); } }
方式三: 实现 Callable 接口
Callable 的 call() 方法会返回执行结果,抛出异常;
ExecutorService :线程池的接口;
Executors: 线程池的工具类
public class MyCallableDemo { public static void main(String[] args) throws ExecutionException, InterruptedException { //方法一 使用线程池方式 ExecutorService executorService = Executors.newFixedThreadPool(2); Future future = executorService.submit(new MyCallable()); future.isDone(); //return true,false 无阻塞 System.out.println(future.get()); // return 返回值,阻塞直到该线程运行结束 //方法二 FutureTask futureTask = new FutureTask(new MyCallable()); Thread thread = new Thread(futureTask); thread.start(); System.out.println(futureTask.get()); } } class MyCallable implements Callable { @Override public String call() throws Exception { System.out.println(Thread.currentThread().getName() + ": 执行 Call 方法"); return Thread.currentThread().getName() + "线程运行完成"; } }
运行结果:
FutureTask 类实现了 Runnable 接口
原文地址:https://www.cnblogs.com/yufeng218/p/9940909.html
时间: 2024-10-12 07:18:00