阅读量:2
在Ubuntu中,使用Java实现多线程主要有两种方法:继承Thread类或实现Runnable接口。下面分别介绍这两种方法的实现步骤。
- 继承Thread类:
步骤1:创建一个类,继承自Thread类。
class MyThread extends Thread {
public void run() {
// 在这里编写多线程执行的代码
System.out.println("线程正在运行: " + Thread.currentThread().getName());
}
}
步骤2:创建MyThread类的对象,并调用start()方法启动线程。
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start(); // 启动线程t1
t2.start(); // 启动线程t2
}
}
- 实现Runnable接口:
步骤1:创建一个类,实现Runnable接口。
class MyRunnable implements Runnable {
public void run() {
// 在这里编写多线程执行的代码
System.out.println("线程正在运行: " + Thread.currentThread().getName());
}
}
步骤2:创建MyRunnable类的对象,并将其传递给Thread类的构造函数。然后调用Thread对象的start()方法启动线程。
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread t1 = new Thread(myRunnable);
Thread t2 = new Thread(myRunnable);
t1.start(); // 启动线程t1
t2.start(); // 启动线程t2
}
}
注意:实现Runnable接口的方法更加灵活,因为它允许你的类继承其他类。而继承Thread类的方法则不能继承其他类,因为Java不支持多继承。在实际开发中,推荐使用实现Runnable接口的方法来实现多线程。
以上就是关于“Ubuntu中Java多线程如何实现”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm