javaSEマルチスレッド演習

javaSEマルチスレッド演習

javaSEマルチスレッド演習

Work3のコードを完成させる

私たちはクラスを提供します:

public class Foo { public void first(){System.out.print( "first");} public void second(){System.out.print( "second");} public void third(){System.out。 print( "third");} } 3つの異なるスレッドA、B、およびCがFooインスタンスを共有します。




1つはfirst()メソッド
を呼び出し1つはsecond()メソッドを呼び出しもう1つは
third()メソッドを呼び出します。
プログラムを設計および変更して、first()の後にsecond()メソッドが実行されるようにしてくださいメソッド、およびthird()メソッドsecond()メソッドの後に実行されます。
例1:

入力:1,2,3
出力: "firstsecondthird"
説明:
3つのスレッドが非同期で開始されます。
1、2、3と入力すると、スレッドAはfirst()メソッドを呼び出し、スレッドBはsecond()メソッドを呼び出し、スレッドCはthird()メソッドを呼び出します。
正しい出力は「firstsecondthird」です。
例2:

入力:
1,3,2出力: "firstsecondthird"
説明:
入力1,3,2は、スレッドAがfirst()メソッドを呼び出し、スレッドBがthird()メソッドを呼び出し、スレッドCがsecond()メソッドを呼び出すことを意味します。 )メソッド。
正しい出力は「firstsecondthird」です。

コード

public class Demo2 {
    
    
    public static void main(String[] args) {
    
    
        Foo foo = new Foo();
        MyRun myRun1 = new MyRun(foo);
        MyRun myRun2 = new MyRun(foo);
        MyRun myRun3 = new MyRun(foo);
        Thread thread1 = new Thread(myRun1);
        Thread thread2 = new Thread(myRun2);
        Thread thread3 = new Thread(myRun3);
        Scanner sc = new Scanner(System.in);
        myRun1.num = sc.nextInt();
        myRun2.num = sc.nextInt();
        myRun3.num = sc.nextInt();
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

class Foo {
    
    
    private boolean firstFinished;
    private boolean secondFinished;

    public Foo() {
    
    
    }

    public synchronized void first() {
    
    
        System.out.println("first");
        firstFinished = true;
        this.notifyAll();
    }


    public synchronized void second() throws InterruptedException {
    
    
        while (!firstFinished) {
    
    
            this.wait();
        }
        System.out.println("second");
        secondFinished = true;
        this.notifyAll();
    }

    public synchronized void third() throws InterruptedException {
    
    
        while (!secondFinished) {
    
    
            this.wait();
        }
        System.out.println("third");
    }
}


class MyRun implements Runnable {
    
    
    Foo foo;
    int num;
    public MyRun(Foo foo) {
    
    
        this.foo = foo;
    }
    @Override
    public void run() {
    
    
        if (num == 1) {
    
    
            foo.first();
        } else if (num == 2) {
    
    
            try {
    
    
                foo.second();
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        } else if (num == 3) {
    
    
            try {
    
    
                foo.third();
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }
    }
}

結果:
ここに画像の説明を挿入

おすすめ

転載: blog.csdn.net/QXANQ/article/details/114046615