在Java中,实现多线程主要有两种方法:继承Thread类或实现Runnable接口。以下是在Ubuntu中使用这两种方法实现多线程的示例。
- 继承Thread类:
// 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(); } }
在Ubuntu终端中,使用以下命令编译和运行:
javac MyThread.java Main.java java Main
- 实现Runnable接口:
// 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(); } }
在Ubuntu终端中,使用以下命令编译和运行:
javac MyRunnable.java Main.java java Main
这两种方法都可以实现在Ubuntu中的Java多线程。