创建线程的几种方式
1、继承Thread类、创建一个类、继承Thread类、并重写run()方法来定义线程执行的逻辑、然后实例化这个类并调用start方法启动线程。
class MyThread extends Thread {
public void run() {
System.out.println("Thread using Thread class is running");
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
2、实现Runnable接口、创建一个类、实现Runnable接口并实现run方法、然后将该Runnable实例传递给Thread类的构造方法、最后调用start方法启动线程。
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread using Runnable interface is running");
}
}
public class ThreadExample {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
3、使用匿名内部类、通过匿名内部类来实现Runnable接口的run方法、直接在Thread类的构造方法中创建并传递。
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
public void run() {
System.out.println("Thread using anonymous inner class is running");
}
});
thread.start();
}
}
4、使用lambda表达式、使用lambda表达式代替匿名类部类来实现Runnable接口的run方法。
public class ThreadExample {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Thread using Lambda expression is running");
});
thread.start();
}
}
5、使用callable和future接口、callable接口类似于runnable接口、但它可以返回并抛出受检异常、可以使用callable接口和future接口来创建线程并获取线程执行的结果
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class ThreadExample {
public static void main(String[] args) {
Callable<String> callable = () -> {
return "Thread using Callable interface is running";
};
FutureTask<String> futureTask = new FutureTask<>(callable);
Thread thread = new Thread(futureTask);
thread.start();
try {
System.out.println(futureTask.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
6、使用线程池、通过java中的ExecutorService和相关类可以创建线程池、然后将任务提交给线程池执行、以便重复利用线程并控制并发度。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(() -> {
System.out.println("Thread in thread pool is running");
});
executor.shutdown();
}
}