分析两种实现多线程的方式:Thread类和Runnable接口

写一个程序,模拟4个售票窗口共同卖100张火车票的程序。

1:使用继承Thread类方式实现()。
2:使用实现Runnable接口方式实现()。

第一种方式(没有共享数据,售票窗口各自买100张票,那4个售票窗口就有400张票)

package com.ljq.test;

/**
* 使用Thread类模拟4个售票窗口共同卖100张火车票的程序
*
* 没有共享数据,每个线程各卖100张火车票
*
*
@author jiqinlin
*
*/
publicclass ThreadTest {

publicstaticvoid main(String[] args){
new MyThread().start();
new MyThread().start();
new MyThread().start();
new MyThread().start();
}

publicstaticclass MyThread extends Thread{
//车票数量
privateint tickets=100;
@Override
publicvoid run() {
while(tickets>0){
System.out.println(
this.getName()+"卖出第【"+tickets--+"】张火车票");
}
}
}
}

                           

第二种方式(共享数据,4个售票窗口共同卖100张票)

package com.lynch.share;

/**
 * 使用Runnable接口模拟4个售票窗口共同卖100张火车票的程序
 * 
 * 共享数据,4个线程共同卖这100张火车票
 *
 * @author Lynch
 */
public class TicketRunnableTest {
    public static void main(String[] args) {
        Runnable runnable = new MyThread();
        new Thread(runnable).start();
        new Thread(runnable).start();
        new Thread(runnable).start();
        new Thread(runnable).start();
    }

    public static class MyThread implements Runnable {
        // 车票数量
        private int tickets = 100;

        public void run() {
            while (tickets > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出第【" + tickets-- + "】张火车票");
            }
        }

    }
}

         

这两种线程创建方式的比较

使用Runnable接口
实际工作中,几乎所有的多线程应用都用实现Runnable这种方式。
Runnable适合多个相同程序代码的线程去处理同一资源的情况。把虚拟CPU(线程)同程序的代码、数据有效的分离,较好的体现了面向对象的设计思想。
避免由于Java的单继承特性带来的局限性。也就是如果新建的类要继承其他类的话,因为JAVA中不支持多继承,就只能实现java.lang.Runnable接口。
有利于程序的健壮性,代码能够被多个线程共享,代码与数据是独立的。

                     
继承Thread类
不能再继承他类了。
编写简单,可以直接操纵线程,无需使用Thread.currentThread()。
请查询API 获得currentThread方法的作用说明。

posted on 2011-04-10 20:41  Ruthless  阅读(14054)  评论(4编辑  收藏  举报