多线程中继承Thread 和实现Runnable接口 的比较(通过售票案例来分析)
通过Thread来实现
Test.java
package com.lanqiao.demo4;
public class Test {
public static void main(String[] args) {
MyThread t1 = new MyThread("张三");
MyThread t2 = new MyThread("李四");
t1.start();
t2.start();
}
}
MyThread.java
package com.lanqiao.demo4;
public class MyThread extends Thread {
private int ticket = 10;
public MyThread(String name) {
super(name);
// TODO Auto-generated constructor stub
}
@Override
public void run() {
while (true) {
if (ticket > 0) {
System.out.println(this.getName() + "卖了一张票" + "还剩下"
+ (--ticket) + "张票");
}
}
}
}
Runnable来实现
MyRunable.java
package com.lanqiao.demo5;
public class MyRunable implements Runnable {
private int ticket = 10;
@Override
public void run() {
while (true) {
if (ticket > 0) {
System.out.println(Thread.currentThread().getName() + "卖了一张票"
+ "还剩下" + (--ticket) + "张票");
}
}
}
}
package com.lanqiao.demo5;
public class Test {
public static void main(String[] args) {
//创建子进程
Thread tr1 = new Thread(new MyRunable());
//启动进程
tr1.start();
Thread tr2 = new Thread(new MyRunable());
tr2.start();
}
}
通过比较分析Thread没有实现资源共享(结果显示一共卖了20张,但是我实际只有10张),买票需要实现数据共享,因为我买了一张别人在买的时候会显示少了一张而不是单独的现实少了。在Runnable的例子中,可以这样实现。结果显示与预定的结果一样