- public class Road {
- private String name = null;
- private List<String> vehicles = new ArrayList<String>();
-
- public Road(String name){
- this.name = name;
- System.out.println("Road"+this.name);
- ExecutorService singleThread = Executors.newSingleThreadExecutor();//返回一个只有一个线程的线程池
- singleThread.execute(new Runnable(){
- @Override
- public void run(){
- for(int i = 0; i<1000; i++){
- try {
- Thread.sleep((new Random().nextInt(10)+1)*1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- synchronized(Road.this){
- vehicles.add(Road.this.name + "_"+i);
- //System.out.println("Add a vehicles:"+Road.this.name + "_"+i);
- }
- }
- }
- });
-
- ScheduledExecutorService timer = Executors.newScheduledThreadPool(1);
- timer.scheduleAtFixedRate(
- new Runnable(){
- @Override
- public void run(){
- if(vehicles.size()>0){
- boolean lighted = Lamp.valueOf(Road.this.name).isLighted();
- if(lighted)
- {
- System.out.println("CurrentThread"+Thread.currentThread());
- System.out.println(vehicles.remove(0)+" is tralling..");
- //这里与前面的 cehicles.add 不会产生同步的问题么?
- }
- }
- }
- },
- 1,
- 1,
- TimeUnit.SECONDS);
- }
- }
复制代码 这是张老师讲交通灯系统的Road部分,我有点困惑,这两个线程的run方法都在操作cehicles,会不会出现同步问题呢?编程应用中什么时候需要加synchronized呢? 请教一下。
|