溫馨提示×

Ubuntu下Java多線程怎么實現

小樊
40
2025-10-09 21:20:02
欄目: 編程語言

在Ubuntu下使用Java實現多線程,主要有兩種方法:繼承Thread類和實現Runnable接口。下面分別介紹這兩種方法的實現步驟。

方法一:繼承Thread

  1. 創建一個繼承自Thread類的子類

    class MyThread extends Thread {
        @Override
        public void run() {
            // 線程執行的代碼
            System.out.println("線程正在運行: " + Thread.currentThread().getName());
        }
    }
    
  2. 創建并啟動線程

    public class Main {
        public static void main(String[] args) {
            MyThread thread1 = new MyThread();
            MyThread thread2 = new MyThread();
            thread1.start(); // 啟動線程1
            thread2.start(); // 啟動線程2
        }
    }
    

方法二:實現Runnable接口

  1. 創建一個實現Runnable接口的類

    class MyRunnable implements Runnable {
        @Override
        public void run() {
            // 線程執行的代碼
            System.out.println("線程正在運行: " + Thread.currentThread().getName());
        }
    }
    
  2. 創建并啟動線程

    public class Main {
        public static void main(String[] args) {
            MyRunnable runnable = new MyRunnable();
            Thread thread1 = new Thread(runnable);
            Thread thread2 = new Thread(runnable);
            thread1.start(); // 啟動線程1
            thread2.start(); // 啟動線程2
        }
    }
    

注意事項

  1. 線程安全:在多線程編程中,需要注意線程安全問題,避免多個線程同時訪問共享資源導致數據不一致。
  2. 線程同步:可以使用synchronized關鍵字或者Lock接口來實現線程同步。
  3. 線程間通信:可以使用wait()、notify()notifyAll()方法來實現線程間的通信。

示例代碼

下面是一個完整的示例代碼,展示了如何使用Runnable接口實現多線程:

class MyRunnable implements Runnable {
    private int count = 0;

    @Override
    public void run() {
        while (count < 5) {
            synchronized (this) {
                System.out.println("線程 " + Thread.currentThread().getName() + " 計數: " + count);
                count++;
                try {
                    Thread.sleep(1000); // 讓線程休眠1秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

public class Main {
    public static void main(String[] args) {
        MyRunnable runnable = new MyRunnable();
        Thread thread1 = new Thread(runnable, "線程1");
        Thread thread2 = new Thread(runnable, "線程2");
        thread1.start();
        thread2.start();
    }
}

在這個示例中,兩個線程共享同一個MyRunnable實例,并且通過synchronized關鍵字確保對count變量的訪問是線程安全的。每個線程會打印計數器的值,并讓線程休眠1秒。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女