class ThreadTest extends Thread{
private int ticket=10;
public void run() {
while (true){
if (ticket>0) {
System.out.println(Thread.currentThread().getName()+" is saling ticket" + ticket--);
}
}
}
}
public class ThreadDemo {
public static void main(String aggs[])
{
new ThreadTest().start();
new ThreadTest().start();
new ThreadTest().start();
new ThreadTest().start();
}
}
继承Thread,执行上面代码的结果是每个线程分别卖出了10张票,这个与实际的问题情况不符。
class RunnableTest implements Runnable{
private int ticket=100;
public void run() {
while(true){
if (ticket>0) {
System.out.println(Thread.currentThread().getName()+" is saling ticket" + ticket--);
}
}
}
}
public class RunnableDemo {
public static void main(String args[]){
RunnableTest rt1=new RunnableTest();
new Thread(rt1).start();
new Thread(rt1).start();
new Thread(rt1).start();
}
}
使用Runnable接口实现执行代码的结果100张票,由三个线程一起卖完。
两种方法实现方式的区别和联系:
在程序开发过程中,只要是触及多线程的问题,基本都以实现Runnable接口为主,因为实现Runnable接口相比继承Thread类相比:
1.避免继承的局限,一个类可以继承多个接口。
2.适合于资源的共享。