阅读量:4
在Java中,实现多线程有两种主要方式:
- 继承Thread类
- 实现Runnable接口
下面是这两种方式的简要介绍和示例代码:
- 继承Thread类
创建一个类,继承自Thread类,并重写其run()方法。run()方法中的代码就是线程要执行的任务。然后创建该类的实例,并调用start()方法来启动线程。
示例代码:
class MyThread extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
public class Main {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.start();
thread2.start();
}
}
- 实现Runnable接口
创建一个类,实现Runnable接口,并重写其run()方法。run()方法中的代码就是线程要执行的任务。然后创建该类的实例,并将其作为参数传递给Thread类的构造函数。最后调用Thread实例的start()方法来启动线程。
示例代码:
class MyRunnable implements Runnable {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
thread1.start();
thread2.start();
}
}
注意:实现Runnable接口的方式更受推荐,因为它允许您的类继承其他类(Java不支持多重继承)。此外,使用Runnable接口可以更好地实现资源共享和线程池。
以上就是关于“java实现多线程的两种方式”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm