作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
考虑这个示例类:
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
已完成。
基本上,call1obj1
和 call1obj2
的线程行为必须限制为 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/
我是一名优秀的程序员,十分优秀!