其实大部分我们用到线程的时候,用哪个都行。偶尔会有不同的时候,我举个我遇到过的例子[code=java]class MyThread extends Thread{
private int ticket = 5;
public void run(){
for(int i = 0; i < 5; i++){
if(this.ticket > 0){
System.out.println("卖票:ticket = "+this.ticket--);
}
}
}
}
public class ThreadDemo{
public static void main(String args[]){
MyThread mt1 = new MyThread();
MyThread mt2 = new MyThread();
MyThread mt3 = new MyThread();
mt1.start();
mt2.start();
mt3.start();
}
}[/code]输出
卖票:ticket = 5
卖票:ticket = 4
卖票:ticket = 3
卖票:ticket = 2
卖票:ticket = 1
卖票:ticket = 5
卖票:ticket = 4
卖票:ticket = 3
卖票:ticket = 5
卖票:ticket = 2
卖票:ticket = 4
卖票:ticket = 1
卖票:ticket = 3
卖票:ticket = 2
卖票:ticket = 1[code=java]class MyThread2 implements Runnable{
private int ticket=5; //一共才5张票
public void run(){ //复写run()方法
for(int i=0;i<50;i++){
if(this.ticket>0){
System.out.println("卖票:ticket ="+this.ticket--);
}
}
}
}
public class RunnableDemo{
public static void main(String args[]){
MyThread2 mt = new MyThread2();
new Thread(mt).start();
new Thread(mt).start();
new Thread(mt).start();
}
}[/code]输出
卖票:ticket =5
卖票:ticket =3
卖票:ticket =4
卖票:ticket =1
卖票:ticket =2
第一个例子里三个线程是彼此独立的,三个窗口各有5张票,各卖各的票,互不干扰
第二个例子里三个线程共享一段代码,相当于三个窗口一起卖5张票
[ 本帖最后由 赵侃 于 2011-08-09 00:30 编辑 ] |