黑马程序员技术交流社区
标题:
交通灯管理系统中新建线程的方式
[打印本页]
作者:
Whero
时间:
2014-11-10 16:48
标题:
交通灯管理系统中新建线程的方式
张孝祥老师在Road和LampController两个类中采用的都是Executors去新建一个线程。我想问用Thread方式建线程行不行?用Thread建的线程没法实现效果,感觉运行时只有一个线程在走!求解。。。。。。
Road代码如下:
import java.util.*;
import java.util.concurrent.*;
public class Road {
private String name;
private List<String> road=new ArrayList<String>();
public Road(String name)
{
this.name=name;
/* ExecutorService pool=Executors.newSingleThreadExecutor();
pool.execute(new Runnable(){
@Override
public void run() {
for(int i=1;i<1000;i++){
try {
Thread.sleep((int)(Math.random()*10000));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
road.add(Road.this.name+"第"+i+"辆车------");
}
}
});
ScheduledExecutorService timer=Executors.newScheduledThreadPool(1);
timer.scheduleAtFixedRate(
new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
if(road.size()>0){
boolean lighted=true;
if(lighted)
System.out.println(road.remove(0)+" driving away...... ");
}
}
},
1,
1,
TimeUnit.SECONDS);*/
new Thread(new Runnable(){
@Override
public void run() {
for(int i=0;i<1000;i++){
System.out.println("加进来没呀");
try {
Thread.sleep((int)(Math.random()*10000));
} catch (InterruptedException e) {
e.printStackTrace();
}
road.add(Road.this.name+" 第"+i+"辆车");
}
}
}).run();
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("干什么呢");
boolean light=Lamp.valueOf(Road.this.name).isLighted();
if(light)
System.out.println(road.remove(0)+" driving away...... ");
//else break;
}
}
}).run();
}
}
复制代码
LampController代码如下:
import java.util.concurrent.*;
public class LampController {
private Lamp currentLamp;
LampController()
{
currentLamp=Lamp.S2N;
currentLamp.light();
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
while(true)
{
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
currentLamp=currentLamp.blackLight();
}
}
}).run();
/* ScheduledExecutorService pool=Executors.newScheduledThreadPool(1);
pool.scheduleAtFixedRate(
new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
currentLamp=currentLamp.blackLight();
}
},
10,
10,
TimeUnit.SECONDS);*/
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2