当前位置: 代码迷 >> J2SE >> 请问怎么把extend Thread的代码改写成实现了runnable
  详细解决方案

请问怎么把extend Thread的代码改写成实现了runnable

热度:319   发布时间:2016-04-24 12:38:12.0
请教如何把extend Thread的代码改写成实现了runnable
书上说用接口的方式比用继承的方式好,因为是初学还没体会到,想问一下如何把下面的代码
改成接口的方式。
public class setPriority{
public static void main(String args[]){
MyThread t1 = new MyThread3("t1");
MyThread t1 = new MyThread3("t2");
t1.start();
t2.start();
}
}

class MyThread3 extend Thread{
MyTherad3(String s){super(s);}

public void run(){
for (int i=1;i<100;i++){
System.out.println(getName()+":"+i);
if(i%10==0){
yield();
}
}
}
}

------解决方案--------------------
在你原有的类上加了些代码
Java code
public class setPriority{     public static void main(String args[]){         MyThread3 t1 = new MyThread3("t1");         MyThread3 t2 = new MyThread3("t2");         t1.start();         t2.start();                 Thread t3 = new Thread(new MyThread4());//以MyThread4类的实例作为参数        t3.start();    } } class MyThread3 extends Thread{     MyThread3(String s){        super(s);    }     public void run(){         for (int i=1;i <100;i++){             System.out.println(getName()+":"+i);             if(i%10==0){                 yield();             }         }     } }class MyThread4 implements Runnable{ //实现Runnable接口    public void run(){        //some codes            }}
  相关解决方案