如何使用继承Thread的方法实现实现资源共享

大家都知道,通过继承Runnable接口实现的多线程可以实现资源共享,那么如何通过继承Thread实现资源共享呢?在前面的文章已经介绍过了两种方式分别能实现资源共享和不能实现资源共享的原因。我们知道,static声明的变量是所有对象共有的,每一个对象对此变量的操作都会保存下来。所以我们可以通过此方式实现继承Thread下的资源共享。实现代码如下:

//尝试通过Thread和static实现资源共享 class MyThread extends Thread { private String name; public static int ticket=10; //通过static声明资源 public MyThread(String name ){ this.name=name; } public void run(){ for(int i = 0;i<100;i++){ if(ticket>0){ System.out.println(this.name+"卖票:"+ticket--); } } } } public class Demo25 { public static void main(String args[]){ MyThread mt1 = new MyThread("mt1"); //声明多个线程 MyThread mt2 = new MyThread("mt2"); MyThread mt3 = new MyThread("mt3"); mt1.start(); mt2.start(); mt3.start(); } }