我说说java中的多线程

 

本人菜鸟,高手有什么见教请留言哦!

情景假设:假如A火车站有4个售票窗口在售出由西安开往阿富汗的K3834次列车的100张火车票。

请看下面的程序代码:

public class Thread001{

public static void main(String[] args) {

 TestThread t=new TestThread();//创建了一个线程对象

t.start();//第一次启动

t.start();//第二次启动

t.start();//第三次启动

t.start();//第四次启动

}

}

class TestThread extends Thread

{

  private int tickets=100;

public void run(){

  while(true){

    if(tickets>0)

  System.out.println(Thread.currentThread().getName()+" 售出"+" 票号为"+tickets--+"的火车票!");

  }

  }

}

l        运行截图:

l        代码分析:

l        此种方法并不能得到我们期盼的效果,运行结果说明只有一个线程在售票而不是我们要求的4个线程。事实告诉我们在java中一个线程对象只能启动一次,无论你调用多少次start()方法,结果都是只有一个线程。

代码修改如下:

public class Thread001{

public static void main(String[] args) {

  new TestThread().start();

   new TestThread().start();

new TestThread().start();

 new TestThread().start();

//创建4个对象并启动四次

}

 

}

//class TestThread implements Runnable

class TestThread extends Thread

{

  private int tickets=100;

public void run(){

  while(true){

    if(tickets>0)

  System.out.println(Thread.currentThread().getName()+" 售出"+" 票号为"+tickets--+"的火车票!");

  }

  

 

}

 

}

l        运行截图:

l        代码分析:

从运行结果来看,是4个线程在售自己各自的100张火车票,而不是我要求的售出共同的100张票,我们只有100张火车票,而他们要售出400张,我晕!

l       前面的教训和经验告诉我们,要达到目的就要用实现Runnable接口的方法;我们修改程序代码如下:

public class Thread001{

public static void main(String[] args) {

  TestThread t=new TestThread();

  new Thread(t).start();

   new Thread(t).start();

    new Thread(t).start();

     new Thread(t).start();

}

 

}

class TestThread implements Runnable

 

{

  private int tickets=100;

public void run(){

  while(true){

    if(tickets>0)

  System.out.println(Thread.currentThread().getName()+" 售出"+" 票号为"+tickets--+"的火车票!");

  }

  }

}

l       运行截图:

总结:我们创建了的4个线程,每个线程调用的是同一个TestThread对象中的run()方法,访问的是同一个对象中的变量(tickets)即100张火车票的资源

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值