线程间的数据共享可以通过两种方式
通过Thread子类创建进程的方法
通过Runnable接口实现进程之间的共享
比较这两种实现进程共享的区别
Thread子类创建进程:
package practice4;
public class ThreadSale extends Thread{
private int tickets=10;
public void run(){
while(true){
if(tickets>0)
System.out.println(getName()+" 售机票第"+tickets--+"号");
else
System.exit(0);
}
}
}
public class App11_4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ThreadSale t1=new ThreadSale();
ThreadSale t2=new ThreadSale();
ThreadSale t3=new ThreadSale();
t1.start();
t2.start();
t3.start();
}
}
运行结果:
Thread-0 售机票第10号
Thread-2 售机票第10号
Thread-1 售机票第10号
Thread-2 售机票第9号
Thread-0 售机票第9号
Thread-2 售机票第8号
Thread-1 售机票第9号
Thread-2 售机票第7号
Thread-2 售机票第6号
Thread-2 售机票第5号
Thread-0 售机票第8号
Thread-2 售机票第4号
Thread-2 售机票第3号
Thread-2 售机票第2号
Thread-2 售机票第1号
Thread-1 售机票第8号
Thread-1 售机票第7号
Thread-1 售机票第6号
Thread-1 售机票第5号
Thread-1 售机票第4号
Thread-1 售机票第3号
Thread-1 售机票第2号
Thread-1 售机票第1号
Thread-0 售机票第7号
Thread-0 售机票第6号
Thread-0 售机票第5号
Thread-0 售机票第4号
Thread-0 售机票第3号
Thread-0 售机票第2号
Runnable接口创建进程:
package practice4;
public class ThreadSale1 implements Runnable{
private int tickets=10;
public void run(){
while(true){
if(tickets>0)
System.out.println(Thread.currentThread().getName()+" 售机票第"+tickets--+"号");
else
System.exit(0);
}
}
}
public class App11_5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ThreadSale1 t=new ThreadSale1();
Thread t1=new Thread(t,"第一售票窗口");
Thread t2=new Thread(t,"第二售票窗口");
Thread t3=new Thread(t,"第三售票窗口");
t1.start();
t2.start();
t3.start();
}
}
第二售票窗口 售机票第9号
第三售票窗口 售机票第8号
第一售票窗口 售机票第10号
第三售票窗口 售机票第6号
第二售票窗口 售机票第7号
第三售票窗口 售机票第4号
第一售票窗口 售机票第5号
第三售票窗口 售机票第2号
第二售票窗口 售机票第3号
第一售票窗口 售机票第1号
可以看出Runnable接口比Thread子类更加实用