Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Java 多執行緒入門:建立、同步與鎖

多執行緒是 Java 的招牌能力之一。本文從最基礎的執行緒建立方式談起,再進一步說明為什麼需要同步,以及同步缺失時會出現什麼問題。

建立執行緒的兩種方式

最直觀的做法是繼承 java.lang.Thread 類,重寫 run() 方法:

/**
 * 定義執行緒類
 */
public class MyThread extends Thread {
    public void run() {
        System.out.println("MyThread.run()");
    }
}
// 使用執行緒
MyThread myThread1 = new MyThread();
MyThread myThread2 = new MyThread();
myThread1.start();
myThread2.start();

另一種更受推薦的做法是實現 java.lang.Runnable 介面,好處是避開單一繼承的限制,讓同一份任務邏輯能被多個執行緒共用:

/**
 * 實現 Runnable 介面的類
 */
public class DoSomething implements Runnable {
    private String name;

    public DoSomething(String name) {
        this.name = name;
    }

    public void run() {
        for (int i = 0; i < 5; i++) {
            for (long k = 0; k < 100000000; k++);
            System.out.println(name + ": " + i);
        }
    }
}
/**
 * 測試 Runnable 實現的多執行緒程式
 */
public class TestRunnable {
    public static void main(String[] args) {
        DoSomething ds1 = new DoSomething("阿三");
        DoSomething ds2 = new DoSomething("李四");
        Thread t1 = new Thread(ds1);
        Thread t2 = new Thread(ds2);
        t1.start();
        t2.start();
    }
}

執行緒同步與鎖

同步的目的,是防止多個執行緒同時存取同一份資料時把資料弄壞。舉例來說,兩個執行緒 ThreadA、ThreadB 都在修改同一個 Foo 物件的資料:

public class Foo {
    private int x = 100;

    public int getX() {
        return x;
    }

    public int fix(int y) {
        x = x - y;
        return x;
    }
}
public class MyRunnable implements Runnable {
    private Foo foo = new Foo();

    public static void main(String[] args) {
        MyRunnable r = new MyRunnable();
        Thread ta = new Thread(r, "Thread-A");
        Thread tb = new Thread(r, "Thread-B");
        ta.start();
        tb.start();
    }

    public void run() {
        for (int i = 0; i < 3; i++) {
            this.fix(30);
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()
                    + " :當前 foo 物件的 x 值= " + foo.getX());
        }
    }

    public int fix(int y) {
        return foo.fix(y);
    }
}

可能的執行結果如下:

Thread-B :當前 foo 物件的 x 值= 40
Thread-A :當前 foo 物件的 x 值= 40
Thread-B :當前 foo 物件的 x 值= -20
Thread-A :當前 foo 物件的 x 值= -20
Thread-B :當前 foo 物件的 x 值= -80
Thread-A :當前 foo 物件的 x 值= -80

可以看到兩個執行緒交錯讀寫同一份資料,數值呈現跳躍。這正是缺乏同步時的典型現象,後續可透過 synchronized 或 Lock 來改善。

Copyright © Linux教程網 All Rights Reserved