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


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

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

第一种方式


package com.ljq.test;

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

public static void main(String[] args){
new MyThread().start();
new MyThread().start();
new MyThread().start();
new MyThread().start();
}

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

 

第二种方式


package com.ljq.test;

/**
* 使用Runnable接口模拟4个售票窗口共同卖100张火车票的程序
*
* 共享数据,4个线程共同卖这100张火车票
*
@author jiqinlin
*
*/
public class RunnableTest {

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方法的作用说明。

智能推荐

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告