Java中开启线程的方法有以下几种:
1. 继承Thread类并重写run()方法:首先创建一个继承自Thread类的类,然后重写run()方法,在run()方法中定义线程要执行的任务。最后创建该类的实例并调用start()方法启动线程。
例如:
class MyThread extends Thread { public void run() { // 线程要执行的任务 } } public class Main { public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); // 启动线程 } }
2. 实现Runnable接口:创建一个实现了Runnable接口的类,然后重写run()方法,在run()方法中定义线程要执行的任务。最后创建该类的实例并将其传递给Thread类的构造函数,然后调用start()方法启动线程。
例如:
class MyRunnable implements Runnable { public void run() { // 线程要执行的任务 } } public class Main { public static void main(String[] args) { MyRunnable runnable = new MyRunnable(); Thread thread = new Thread(runnable); thread.start(); // 启动线程 } }
3. 使用匿名类实现Runnable接口:与第2种方式类似,只是使用匿名类来实现Runnable接口,并直接在Thread类的构造函数中创建该匿名类的实例。
例如:
public class Main { public static void main(String[] args) { Runnable runnable = new Runnable() { public void run() { // 线程要执行的任务 } }; Thread thread = new Thread(runnable); thread.start(); // 启动线程 } }
4. 使用Java 8的Lambda表达式:在Java 8中,可以使用Lambda表达式来简化线程的创建和开启。
例如:
public class Main { public static void main(String[] args) { Thread thread = new Thread(() -> { // 线程要执行的任务 }); thread.start(); // 启动线程 } }
无论使用哪种方式,线程启动后会执行run()方法中的代码,从而实现多线程的并发执行。
财旺号所有作品(图文、网盘、音视频)收集于网络,均由用户自行上传分享,仅供网友学习交流,不声明或保证其内容的正确性,如发现本站有涉嫌抄袭侵权/违法违规的内容。请发送邮件至 1790309299@qq.com 举报,一经查实,本站将立刻删除。