gpt4 book ai didi

java - 如何将线程行为限制为调用它们的方法?

转载 作者:行者123 更新时间:2023-12-01 09:57:17 25 4
gpt4 key购买 nike

考虑这个示例类:

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 应该等到 call1obj1 >call1obj2 已完成。

基本上,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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com