A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© Peach2014 中级黑马   /  2014-8-25 17:48  /  1363 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 Peach2014 于 2014-8-25 17:51 编辑

张孝祥老师7K面试一中的交通信号灯中,Road类中的代码如下
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.Random;
  4. import java.util.concurrent.ExecutorService;
  5. import java.util.concurrent.Executors;
  6. import java.util.concurrent.ScheduledExecutorService;
  7. import java.util.concurrent.TimeUnit;

  8. public class Road {
  9. private List<String> vechicles = new ArrayList<String>();
  10. private String name = null;
  11. public Road(String name){
  12. this.name = name;
  13. ExecutorService pool =Executors.newSingleThreadExecutor();
  14. //执行一个线程
  15. pool.execute(new Runnable(){
  16. public void run(){
  17. for(int i = 1; i < 1000; i++){
  18. try {

  19. Thread.sleep((new Random().nextInt(10) + 1) * 1000);
  20. } catch (InterruptedException e) {
  21. e.printStackTrace();
  22. }
  23. vechicles.add(Road.this.name + "_" + i);
  24. }
  25. }
  26. });
  27. //启动一个定时器
  28. ScheduledExecutorService timer = Executors.newScheduledThreadPool(1);
  29. timer.scheduleAtFixedRate(
  30. new Runnable(){
  31. public void run(){
  32. if(vechicles.size() > 0){
  33. boolean lighted = Lamp.valueOf(Road.this.name).isLighted();
  34. if(lighted){
  35. System.out.println(vechicles.remove(0) + " is traversing!");
  36. }
  37. }
  38. }
  39. },
  40. 1,
  41. 1,
  42. TimeUnit.SECONDS);
  43. }
  44. }
复制代码
在构造函数中程序的线程池中的代码没有执行完,为什么定时器中的代码也可以同时执行。
这是一个什么样的机制。构造函数中的代码不应该是从上往下执行的吗?在Sleep的时候后面的代码不是应该会阻塞吗?
不是很理解,求大神指导!


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马