面试的时候代码题考到了多线程,很悲催的没有过,回头看看自己确实基本知识不扎实,另外准备面试的时候跑偏了方向,研究算法数据结构研究了半天。。。结果面试的重点考点是对于java基础知识,和常用包的掌握,而java使用时最重要的原则,就是donot reinvent the wheel(不要重新发明轮子),基础知识和常用包的掌握非常重要,给正在准备面试的同学提醒一下。
Can you pass a Thread object to Executor.execute? Would such an invocation make sense?
能否将Thread对象传入Executor并且运行?这样做是否有意义?
复制代码
查看以下代码:
Compile and run 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);
}
}
The application should print out "Mares do eat oats." Is it guaranteed to always do this? If not, why not? Would it help to change the parameters of the two invocations of Sleep? How would you guarantee that all changes to message will be visible in the main thread?
复制代码
这段代码应该始终打印出: Mares do eat oats。但是能否保证程序总是如此执行?如果不,为何?改变sleep的参数对于此目的有帮助吗?如果是你,你如何保证所有对于message的改变对于主线程来说都是可见的?