温馨提示×

java线程的创建方式有哪些

小亿
86
2023-11-08 11:55:30
栏目: 编程语言

Java线程的创建方式有以下几种:

  1. 继承Thread类:创建一个继承自Thread类的子类,并重写run()方法来定义线程执行的任务。然后可以通过创建子类的实例来创建和启动线程。
class MyThread extends Thread {
    public void run() {
        // 线程执行的任务
    }
}
MyThread thread = new MyThread();
thread.start();
  1. 实现Runnable接口:创建一个实现了Runnable接口的类,并实现其run()方法来定义线程执行的任务。然后可以通过创建Runnable实现类的实例来创建Thread实例,并调用start()方法来启动线程。
class MyRunnable implements Runnable {
    public void run() {
        // 线程执行的任务
    }
}
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
  1. 使用匿名内部类:可以在创建Thread对象时使用匿名内部类来实现run()方法。这种方式比较简洁,适用于定义较为简单的线程任务。
Thread thread = new Thread() {
    public void run() {
        // 线程执行的任务
    }
};
thread.start();
  1. 使用Callable和Future:通过创建实现Callable接口的类,并实现其call()方法来定义线程执行的任务。然后可以使用ExecutorService的submit()方法提交Callable任务,并返回一个Future对象,通过Future对象可以获取线程执行结果。
class MyCallable implements Callable<Integer> {
    public Integer call() throws Exception {
        // 线程执行的任务,返回一个结果
        return 1;
    }
}
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<Integer> future = executor.submit(new MyCallable());
  1. 使用线程池:可以使用ExecutorService来管理线程池,通过执行Runnable或Callable任务来创建线程。
ExecutorService executor = Executors.newFixedThreadPool(1);
executor.execute(new Runnable() {
    public void run() {
        // 线程执行的任务
    }
});

0