考虑以下示例类:

public class Multithreading extends Thread {
    static int i = 0;

    public static void main(String args[]) throws InterruptedException {

        call1();
        call2();
    }

    private static void call2() {

        Multithreading call2obj1 = new Multithreading() {
            public void run() {

            }
        };
        call2obj1.start();

    }

    private static void call1() {

        Multithreading call1obj1 = new Multithreading() {
            public void run() {
                System.out.println("call1obj1");
                sleep(5000);
            }
        };
        Multithreading call1obj2 = new Multithreading() {
            public void run() {
                System.out.println("call1obj2");
                sleep(5000);
            }
        };
        call1obj1.start();
        call1obj2.start();

    }
}


我要的是让call2()等到call1()完全完成。即call1obj2不必等到call1obj1执行完毕,但call2obj1应该等到call1obj1call1obj2都完成。

基本上call1obj1call1obj2的线程行为必须限制为call1()

那可能吗?

最佳答案

这是使用CountDownLatch的解决方案:

public class Multithreading extends Thread {
static int i = 0;

private static CountDownLatch LATCH;

public static void main(String args[]) throws InterruptedException {

    // Initialize the latch with the number of threads to finish
    LATCH = new CountDownLatch(2);

    call1();

    // Main thread will wait until all thread finished
    LATCH.await();

    call2();
}

private static void call2() {

    Multithreading call2obj1 = new Multithreading() {
        public void run() {
            System.out.println("call2obj1");
        }
    };
    call2obj1.start();

}

private static void call1() {

    Multithreading call1obj1 = new Multithreading() {
        public void run() {
            System.out.println("call1obj1");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                LATCH.countDown();
            }
        }
    };
    Multithreading call1obj2 = new Multithreading() {
        public void run() {
            System.out.println("call1obj2");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                LATCH.countDown();
            }
        }
    };
    call1obj1.start();
    call1obj2.start();

}


}

关于java - 如何将线程行为限制为调用它们的方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37093240/

10-12 03:05