问题与练习:并发
Questions
- 您可以将
Thread
对象传递给Executor.execute
吗?这样的调用有意义吗?
Exercises
- 编译并运行BadThreads.java:
public class BadThreads {
static String message;
private static class CorrectorThread
extends Thread {
public void run() {
try {
sleep(1000);
} catch (InterruptedException e) {}
// Key statement 1:
message = "Mares do eat oats.";
}
}
public static void main(String args[])
throws InterruptedException {
(new CorrectorThread()).start();
message = "Mares do not eat oats.";
Thread.sleep(2000);
// Key statement 2:
System.out.println(message);
}
}
该应用程序应打印出“母马吃燕麦”。是否保证总是这样做?如果没有,为什么不呢?更改Sleep
的两个调用的参数是否有帮助?您如何保证对message
的所有更改在主线程中可见?
- 修改Guarded Blocks中的生产者-Consumer 示例,以使用标准库类而不是
Drop
类。