Igo*_*gor 2 java multithreading
我有一个函数需要在布尔变量为真时调用.我尝试在线程中使用while循环,但它不起作用.这是我尝试过的:
public class MyRunnable implements Runnable {
public void run() {
while (true) {
if (conditions == true) {
System.out.println("second");
break;
}
}
}
public static void main(String args[]) {
boolean condition = false;
(new Thread(new MyRunnable())).start();
System.out.println("first\n");
// set conndition to true
condition = true;
}
}
Run Code Online (Sandbox Code Playgroud)
结果应该是:
first
second
Run Code Online (Sandbox Code Playgroud)
Mar*_*nik 14
不要忙 - 等待这样的条件.使用阻塞习语.对于你的简单案例,你会逃避new CountDownLatch(1).首先,这是你的代码,但修复了编译和运行你期望的方式:
public class MyRunnable implements Runnable {
volatile boolean condition = false;
public void run() {
while (true) {
if (condition) {
System.out.println("second");
break;
}
}
}
public static void main(String args[]) {
final MyRunnable r = new MyRunnable();
new Thread(r).start();
System.out.println("first\n");
r.condition = true;
}
}
Run Code Online (Sandbox Code Playgroud)
为了比较,一个程序有CountDownLatch:
public class MyRunnable implements Runnable {
final CountDownLatch latch = new CountDownLatch(1);
public void run() {
try { latch.await(); } catch (InterruptedException e) {}
System.out.println("second");
}
public static void main(String args[]) {
final MyRunnable r = new MyRunnable();
new Thread(r).start();
System.out.println("first\n");
r.latch.countDown();
}
}
Run Code Online (Sandbox Code Playgroud)
要真正注意到差异,请添加一个Thread.sleep(20000)后续内容println("first")并听取计算机风扇声音的差异,努力消耗第一个程序浪费的能量.
| 归档时间: |
|
| 查看次数: |
9497 次 |
| 最近记录: |