在Java中,实现多线程主要有两种方法:继承Thread类或实现Runnable接口。以下是在Ubuntu上使用这两种方法实现多线程的示例。
- 继承Thread类
创建一个名为MyThread的类,继承Thread类,并重写run()方法。在run()方法中编写线程执行的代码。
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的类,用于启动线程。
public class Main { public static void main(String[] args) { MyThread t1 = new MyThread(); MyThread t2 = new MyThread(); t1.start(); t2.start(); } }
编译并运行Main类:
javac Main.java java Main
- 实现Runnable接口
创建一个名为MyRunnable的类,实现Runnable接口,并重写run()方法。在run()方法中编写线程执行的代码。
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的类,用于启动线程。
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(); } }
编译并运行Main类:
javac Main.java java Main
这两种方法都可以在Ubuntu上实现多线程。在实际应用中,推荐使用实现Runnable接口的方法,因为它更符合面向对象的设计原则,避免了单继承的限制。