![]() |
#2
a3510218172018-05-24 20:08
|
方式一:继承Thread类,重写run方法

package com.xiaoa.thread;
public class MyThread extends Thread {
@Override
public void run() {
super.run();
System.out.println("MyThread.run()");
}
}
public class MyThread extends Thread {
@Override
public void run() {
super.run();
System.out.println("MyThread.run()");
}
}
方式二:实现Runnable接口,重写run方法

package com.xiaoa.thread;
public class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println("MyRunnable.run()");
}
}
public class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println("MyRunnable.run()");
}
}
测试代码:
package com.xiaoa.test;
import com.xiaoa.thread.MyRunnable;
import com.xiaoa.thread.MyThread;
public class Test {
public static void main(String[] args) throws Exception {
MyThread th1 = new MyThread();
th1.start();
th1.sleep(100l);
System.out.println("--------------------------");
Thread.currentThread().sleep(100l);
MyRunnable th = new MyRunnable();
Thread th2 = new Thread(th);
th2.start();
}
}
测试结果:
MyThread.run()
--------------------------
MyRunnable.run()
--------------------------
MyRunnable.run()