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 我觉得话应该这么说: