在Ubuntu下使用Java实现多线程,可以通过以下两种方式:
- 继承Thread类
- 实现Runnable接口
下面分别介绍这两种方法的实现步骤:
方法一:继承Thread类
- 创建一个类,继承自Thread类。
- 重写run()方法,编写多线程需要执行的代码。
- 创建该类的对象,并调用start()方法启动线程。
示例代码:
// MyThread.java public class MyThread extends Thread { @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName() + ": " + i); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } // Main.java public class Main { public static void main(String[] args) { MyThread t1 = new MyThread(); MyThread t2 = new MyThread(); t1.start(); t2.start(); } }
方法二:实现Runnable接口
- 创建一个类,实现Runnable接口。
- 实现run()方法,编写多线程需要执行的代码。
- 创建该类的对象,并将其作为参数传递给Thread类的构造函数,创建Thread对象。
- 调用Thread对象的start()方法启动线程。
示例代码:
// MyRunnable.java public class MyRunnable implements Runnable { @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName() + ": " + i); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } // Main.java 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(); t2.start(); } }
这两种方法都可以实现多线程,但通常推荐使用实现Runnable接口的方式,因为它更符合面向对象的设计原则,避免了Java单继承的限制。