本帖最后由 王广亚 于 2013-8-25 15:02 编辑
- class Ticket implements Runnable{
- private int tick=1000;
- String name;
- Object obj=new Object();
- // @Override
- public Ticket(String name){
- this.name=name;
- }
- public void run() {
- System.out.println(Thread.currentThread().getName()+"----------------");
- while(true){
- synchronized(obj){
- if(tick>0){ //<font color="red">问题:此处问什么要加个if判断语句,既然有while语句为何不把这个位置的if语句替换成while(tick>0)。而把上面的while去掉呢?</font>
- try{
- Thread.sleep(12);
- }catch(Exception e){}
- System.out.println(this.getName()+"号列车"+Thread.currentThread().getName()+". ..sale"+tick--);
- }
- }
- }
- }
- private String getName() {
- // TODO Auto-generated method stub
- return name;
- }
- }
- public class TickeDemo {
- public static void main(String[] args) {
- Ticket t=new Ticket("-k2038-");//
- Thread t1=new Thread(t,"-001窗口");
- Thread t2=new Thread(t,"-002窗口");
- Thread t3=new Thread(t,"-003窗口");
- Thread t4=new Thread(t,"-004窗口");
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
- }
复制代码 |