创建线程的三种方式
1. 继承Thread类,重写run方法
public class MyThread extends Thread {
public void run() {
System.out.println("Hello from MyThread!");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
// 输出结果
Hello from MyThread!
2. 实现Runnable接口,实现run方法
public class MyRunnable implements Runnable {
public void run() {
System.out.println("Hello from MyRunnable!");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
// 输出结果
Hello from MyRunnable!
2. 使用Callable和Future创建有返回值的线程
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
public class MyCallable implements Callable<String> {
public String call() {
return "Hello from MyCallable!";
}
}
public class Main {
public static void main(String[] args) throws Exception {
Callable<String> callable = new MyCallable();
FutureTask<String> futureTask = new FutureTask<>(callable);
Thread thread = new Thread(futureTask);
thread.start();
String result = futureTask.get();
System.out.println(result);
}
}
// 输出结果
Hello from MyCallable!
以上是Java创建线程的三种方式,分别使用了
- 继承Thread类、
- 实现Runnable接口、
- 使用Callable和Future创建有返回值的线程。
通过这三种方式,我们可以灵活地创建多线程应用程序。
标签:Hello,Java,thread,Thread,public,线程,new,三种,class From: https://www.cnblogs.com/ldh-0319/p/17279297.html