壹酒酒柒
2018-08-28 00:08
为什么代码中的第二个类是用接口来写的呢
继承Thread和实现Runnable其区别主要在于共享数据,Runnable接口是可以共享数据的,多个Thread可以同时加载一个Runnable,当各自Thread获得CPU时间片的时候开始运行Runnable,Runnable里面的资源被共享。
而例子中
class Actress implements Runnable{
static int count = 0;
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "是一个演员!");
boolean courrent = true;
while(courrent) {
System.out.println(Thread.currentThread().getName() + "登台演出第" + (++count) + "场次!");
if(count>=100){
courrent = false;
}
if(count%10 == 0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println(Thread.currentThread().getName() + "演出结束了");
}
}与
public class Actor extends Thread {
static int count = 0;
public void run() {
System.out.println(getName() + "是一个演员!");
boolean courrent = true;
while(courrent) {
System.out.println(getName() + "登台演出第" + (++count) + "场次!");
if(count>=100){
courrent = false;
}
if(count%10 == 0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println(getName() + "演出结束了");
}
public static void main(String[] args) {
Thread actorThread = new Actor();
actorThread.setName("Mr.Thread");
actorThread.start();
Thread actress = new Thread(new Actress(),"Ms.Runnable");
actress.start();
}
}主要是说明不管是继承Thread还是实现Runnable接口我们都可以创建线程。在实际开发中大多数情况下是实现Runnable接口的,因为它可以共享数据。
深入浅出Java多线程
186065 学习 · 502 问题
相似问题