next up previous
Next: 12.3 synchronizedブロック Up: 12 同期処理 Previous: 12.1 スレッドの終了待ち join

12.2 排他(mutual exclusion)制御

独立の並行して走るスレッドから 同じオブジェクトをアクセスするプログラムコードは きわどい領域(critical sections)と呼ばれる.

// synchronize1.java
class synchronize1
{
    public static void main(String args[])
    {
        Shared shared = new Shared();

        CustomThread4 thread1 =
            new CustomThread4(shared, "one");
        CustomThread4 thread2 =
            new CustomThread4(shared, "two");
        CustomThread4 thread3 =
            new CustomThread4(shared, "three");
        CustomThread4 thread4 =
            new CustomThread4(shared, "four");

        try {
            thread1.join();
            thread2.join();
            thread3.join();
            thread4.join();
        } catch(InterruptedException e) {}
    }
}

class CustomThread4 extends Thread
{
    Shared shared;

    public
      CustomThread4(Shared shared, String string)
    {
        super(string);
        this.shared = shared;
        start();
    }

    public void run() {
        shared.doWork(
            Thread.currentThread().getName());
    }
}

class Shared
{
    void doWork(String string)
    {
        System.out.println("Starting " + string);
        try {
            Thread.sleep((long)
                         (Math.random() * 500));
        } catch (InterruptedException e) {}
        
        System.out.println("Ending " + string);
    }
}

これを実行すると,

% java synchronize1
Starting one
Starting two
Starting three
Starting four
Ending one
Ending two
Ending four
Ending three
という形で,Endingの順番がStartingの順番と 異なる.

generated through LaTeX2HTML. M.Inaba 平成18年5月7日