第一、Runnable、Thread中的run方法和自定义的run方法之间的关系:
1 interface Runnable{ 2 public abstract void run(); 3 } //remove method body 4 5 public class Thread implements Runnable { 6 private Runnable target; //封装 7 public Thread(Runnable target,String name){ //构造函数,name是线程的名称 8 init(target); 9 } 10 11 private void init(Runnable target2) { //检验关口,给属性赋值 12 this.target = target; 13 } 14 15 public void run() { 16 if(target != null){ 17 target.run(); //此run方法指的是自定义的run方法,即Runable中的run方法 18 //整个过程中,只有一个对象,只有这个对象有能力调用自定 19 //义的run方法。 20 } 21 } 22 } 23 class MyThread implements Runnable{ 24 public void run() { //自定义的run方法 25 26 } 27 }
第二、Thread和Runnable比较
1)Thread
1 package com.threaddemo; 2 3 class MyThread extends Thread{ 4 private int ticket = 5; 5 public void run(){ 6 for(int i=0;i<100;i++){ 7 if(ticket>0){ 8 System.out.println(ticket--); 9 } 10 } 11 } 12 } 13 14 public class ThreadDemo04 { 15 16 public static void main(String[] args) { 17 MyThread mt1 = new MyThread(); 18 MyThread mt2 = new MyThread(); 19 MyThread mt3 =new MyThread(); 20 mt1.start(); 21 mt2.start(); 22 mt3.start(); 23 } 24 25 }
2)
1 package com.runnabledemo; 2 3 class MyThread implements Runnable{ 4 private int ticket =5; 5 public void run(){ 6 for(int i=0;i<100;i++){ 7 if(ticket>0){ 8 System.out.println(ticket--); 9 } 10 } 11 } 12 } 13 14 public class RunnableDemo02 { 15 16 public static void main(String[] args) { 17 MyThread my = new MyThread(); 18 new Thread(my).start(); 19 new Thread(my).start(); 20 new Thread(my).start(); 21 } 22 }
从以上两个程序可知:在使用Runable的整个过程中,只产生一个能操作ticket的对象,实现多个线程共同处理同一资源(ticket),即实现资源的共享;
而在使用Thread时,每一个New都会产生一个拥有自己的ticket的对象,即每个对象都有各自的ticket,各操作各的,三个ticket数值变化互不影响。