!!!!!!Thread和Runnable都是可以实现资源共享的!!!!只要把资源作为参数传递给进程Thread的构造函数就行,因为这样start()方法调用的就是g1.run()Goods g1 = new Goods("鸡翅盒饭",100);Thread t1 = new Thread(g1,"小明");
既然都可以那么为什么要有Runnable?
因为类只能继承一个父类,继承了Thread就没法继承别的类了,,
有了Runnable接口就可以继承别的类了,增强了程序的拓展性
我的理解是这样的
我们之所以要继承Thread是因为在调用线程对象的start()方法开启线程时, start()会自动将Thread中的
run()作为执行代码,因此我们必须用我们实际想要执行的代码来覆盖run()方法,而覆盖就必须继承
Thread,,,又因为继承Thread有缺点,所以为了不覆盖,,可以在创建线程对象时将包含run方法的资源对象
作为Thread构造器参数target(使用Runnable时必须把资源对象作为参数传给Thread构造器,不然没用)
public void run() {
if (target != null) {
target.run();
}
}
这是Thread中run()方法的源码,可以看出有了参数(资源对象)后,直接执行target即资源对象中的run,,
Runnable接口只是为了规范方法名run(),对执行哪个run这个过程没有影响,,不写的话会报错
The constructor Thread(Goods, String) is undefined*(不知道报错的源码在哪,,,,没找到,,)
1继承Thread(3个线程处理一个资源)
1 package noname; 2 class Goods extends Thread { 3 String name ; 4 int num ; 5 Goods(String name, int num) { 6 this.name = name; 7 this.num = num; 8 } 9 void eat() { 10 while(num>0){ 11 System.out.println(name+" "+num--+",,,"+Thread.currentThread().getName()+"吃的"); 12 } 13 } 14 public void run() { 15 eat(); 16 } 17 18 } 19 class Productor{ 20 21 } 22 class Consumer{ 23 24 } 25 public class Test { 26 public static void main(String[] args) { 27 Goods g1 = new Goods("鸡翅盒饭",100); 28 Thread t1 = new Thread(g1,"小明"); 29 Thread t2 = new Thread(g1,"小红"); 30 Thread t3 = new Thread(g1,"小黄"); 31 t1.start(); 32 t2.start(); 33 t3.start(); 34 } 35 36 }
2实现Runnable接口
1 package noname; 2 class Goods implements Runnable { 3 String name ; 4 int num ; 5 Goods(String name, int num) { 6 this.name = name; 7 this.num = num; 8 } 9 void eat() { 10 while(num>0){ 11 System.out.println(name+" "+num--+",,,"+Thread.currentThread().getName()+"吃的"); 12 } 13 } 14 public void run() { 15 eat(); 16 } 17 18 } 19 class Productor{ 20 21 } 22 class Consumer{ 23 24 } 25 public class Test { 26 public static void main(String[] args) { 27 Goods g1 = new Goods("鸡翅盒饭",100); 28 Thread t1 = new Thread(g1,"小明"); 29 Thread t2 = new Thread(g1,"小红"); 30 Thread t3 = new Thread(g1,"小黄"); 31 t1.start(); 32 t2.start(); 33 t3.start(); 34 } 35 36 }
这里可以看出 我只是把extends Thread改为了implements Runnable 并且结果没有变化