Java开启多线程的常见方法有以下几种:
- 继承Thread类:定义一个类继承Thread类,并重写run()方法,然后创建该类的实例,并调用start()方法启动线程。
class MyThread extends Thread { public void run() { // 线程执行的代码 } } MyThread thread = new MyThread(); thread.start();
- 实现Runnable接口:定义一个类实现Runnable接口,并实现其run()方法,然后创建Thread类的实例,将Runnable对象作为参数传递给Thread对象,最后调用Thread的start()方法启动线程。
class MyRunnable implements Runnable { public void run() { // 线程执行的代码 } } MyRunnable runnable = new MyRunnable(); Thread thread = new Thread(runnable); thread.start();
- 使用Callable和Future:定义一个类实现Callable接口,并实现其call()方法,然后创建ExecutorService对象,将Callable对象提交给ExecutorService的submit()方法,返回一个Future对象,通过调用Future对象的get()方法获取线程的返回值。
class MyCallable implements Callable{ public Integer call() throws Exception { // 线程执行的代码 return 1; } } MyCallable callable = new MyCallable(); ExecutorService executor = Executors.newFixedThreadPool(1); Future future = executor.submit(callable);
- 使用线程池:创建一个ExecutorService对象,通过调用其方法来提交Runnable或Callable任务,线程池会自动管理线程的生命周期。
ExecutorService executor = Executors.newFixedThreadPool(5); executor.execute(new Runnable() { public void run() { // 线程执行的代码 } });
这些方法都可以用来创建并启动一个新的线程,根据具体情况选择使用。