想知道用如下两种方法创建的线程共享变量时,有没有什么不同?或是哪一种好一些?
方法1,继承Thread类,使用静态变量:- public static void main(String [] args){
- MutliThread m1=new MutliThread("Window 1");
- MutliThread m2=new MutliThread("Window 2");
- m1.start();
- m2.start();
- }
- class MutliThread extends Thread{
- private static int ticket=100;//共享变量
- public void run(){
- while(ticket>0){
- System.out.println(ticket--+" is saled by "+Thread.currentThread().getName());
- }
- }
- }
复制代码 方法2,实现Runnable接口:- public static void main(String [] args){
- MutliThread m1=new MutliThread("Window 1");
- MutliThread m2=new MutliThread("Window 2");
- Thread t1=new Thread(m1);
- Thread t2=new Thread(m2);
- t1.start();
- t2.start();
- }
- class MutliThread implements Runnable{
- private int ticket=100;//共享变量
- public void run(){
- while(ticket>0){
- System.out.println(ticket--+" is saled by "+Thread.currentThread().getName());
- }
- }
- }
复制代码 |