Runnable 和 Thread
我们都知道创建线程有两个方法:? 一是通过继承Thread类;二是向Thread类传递一个Runnable对象.
比如说一个售票站有四个窗口卖票,我们要设计四个线程
第一种方法:传递一个Runnable对象.
public class MyThread{ public static void main(String[] args) { TestThread tt = new TestThread(); new Thread(tt).start(); new Thread(tt).start(); new Thread(tt).start(); new Thread(tt).start(); }} class TestThread implements Runnable{ public int ticket = 100; public void run() { while(ticket>0) { System.out.println(Thread.currentThread().getName()+"is saling ticket"+ticket--); } }}?
?二.通过继承Thread类
public class MyThread{ public static void main(String[] args) { TestThread tt1 = new TestThread().start(); TestThread tt2= new TestThread().start(); TestThread tt3 = new TestThread().start();TestThread tt4 = new TestThread().start();}}class TestThread implements Runnable{ public int ticket = 100; public void run() { while(ticket>0) { System.out.println(Thread.currentThread().getName()+"is saling ticket"+ticket--); } }}
?结论:
方法一中四个线程是合作卖100张,而方法二中是四个线程分别各卖100张,就是说四个线程都会卖同一张票四次。
也就是说Runnalbe 是多个对象同时跑一个run,Thread是各自跑各自的
?
1 楼 dotjar 2012-04-20 我觉得话应该这么说:引用
TestThread tt = new TestThread();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
这里只有一个线程实例,所以ticket数据共享;
而
引用
TestThread tt1 = new TestThread().start();
TestThread tt2= new TestThread().start();
TestThread tt3 = new TestThread().start();
TestThread tt4 = new TestThread().start();
各有各自的ticket,各自属于各自的实例,不存在数据共享问题。
这就是说,上边那个是线程间数据共享的例子,有如火车售票。
我也是来总结下,沾沾楼主的光。
楼主万福! 2 楼 xiaoxiecomeon 2012-04-26 你这个程序一存在线程的时间片相互抢占的问题,运行时间长了很可能会卖出0、-1、-2这张票。你可以在while输出的后面加一句sleep(1)试一下,会找到问题的。