ubuntu

Java在Ubuntu中如何实现多线程

小樊
36
2025-03-10 09:07:13
栏目: 编程语言
Ubuntu服务器限时活动,0元免费领! 查看>>

在Java中,实现多线程主要有两种方法:继承Thread类或实现Runnable接口。以下是在Ubuntu中使用这两种方法实现多线程的示例。

  1. 继承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
  1. 实现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多线程。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

相关推荐:Java在Ubuntu上如何实现多线程

0
看了该问题的人还看了