JAVA线程的建立方法
在JAVA中,线程的建立主要有两种方式:继承Thread类和实现Runnable接口。每种方法各有优缺点,适用于不同场景。
继承Thread类
通过继承Thread类并重写run()方法可以创建线程。以下是示例代码:
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
继承Thread类的方式简单直接,但由于JAVA不支持多继承,如果类已经继承了其他类,就无法再继承Thread类。
实现Runnable接口
通过实现Runnable接口并实现run()方法可以创建线程。以下是示例代码:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
实现Runnable接口的方式更加灵活,因为可以避免单继承的限制,同时更适合多线程共享资源的场景。
使用Lambda表达式简化
从JAVA 8开始,可以使用Lambda表达式进一步简化Runnable接口的实现:
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Thread is running");
});
thread.start();
}
}
这种方式代码更简洁,适用于简单的线程任务。
使用Callable和Future
如果需要线程有返回值,可以使用Callable接口和Future:
import java.util.concurrent.*;
class MyCallable implements Callable<String> {
public String call() throws Exception {
return "Thread result";
}
}
public class Main {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new MyCallable());
System.out.println(future.get());
executor.shutdown();
}
}
Callable接口允许线程返回结果,并通过Future获取结果,适用于需要返回值的场景。
使用线程池
为了提高线程管理效率,可以使用线程池:
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
executor.execute(() -> {
System.out.println("Thread is running");
});
}
executor.shutdown();
}
}
线程池可以复用线程,减少线程创建和销毁的开销,适用于高并发场景。