在jdk中有一个Thread(Runnable target)构造方法。Runnable接口只有一个run方法。
当使用Thread(Runnable target)方法创建线程对象时,需为该方法传递一个Runnable接口的类对象。这样创建的线程将调用那个实现了Runnable接口的类对象中的run方法作为其运行代码,而不再调用Thread类中的run方法。
- public class ThreadDemo3 {
-
-
public static void main(String[] args) {
-
-
TestThread3 tt = new TestThread3();
-
Thread t = new Thread(tt);
-
t.start();
-
while(true){
-
System.out.println("main thread is runing...");
-
try {
-
Thread.currentThread().sleep(1000);
-
} catch (InterruptedException e) {
-
e.printStackTrace();
-
}
-
}
-
}
-
}
-
-
class TestThread3 implements Runnable{
-
-
@Override
-
public void run() {
-
while(true){
-
System.out.println(Thread.currentThread().getName() + " is runing***");
-
try {
-
Thread.sleep(1000);
-
} catch (InterruptedException e) {
-
e.printStackTrace();
-
}
-
}
-
-
}
-
-
}
测试运行结果:
main thread is runing...
main thread is runing...
Thread-0 is runing***
main thread is runing...
Thread-0 is runing***
main thread is runing...
Thread-0 is runing***
main thread is runing...
Thread-0 is runing***
main thread is runing...
Thread-0 is runing***
main thread is runing...
Thread-0 is runing***
Thread-0 is runing***
实现runnable接口相对于继承Thread类来说,有如下好处:
适合多个相同程序代码的线程去处理同一资源的情况。
可以避免由于java的单继承带来的局限。
代码能被多个线程共享,代码与数据是独立的。
事实上,几乎所有的多线程应用都可通过实现Runnable接口来实现。
阅读(806) | 评论(0) | 转发(0) |