多线程的实现方法
1、继承Thread类
示例代码
public class ThreadDaemon extends Thread {
public void run(){
for(int i=0;i<100;i++){
System.out.println(getName()+":"+i);
}
}
}
public class MyThreadDemo {
public static void main(String[] args) {
ThreadPriority tp1= new ThreadPriority();
ThreadPriority tp2= new ThreadPriority();
ThreadPriority tp3= new ThreadPriority();
tp1.setName("高铁");
tp2.setName("飞机");
tp3.setName("汽车");
tp1.start();
tp2.start();
tp3.start();
}
}
2、实现Runnable接口
示例代码
public class MyRunnable implements Runnable{
@Override
public void run() {
for(int i=0;i<100;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
public class MyRunnableDemo {
public static void main(String[] args) {
MyRunnable my = new MyRunnable();
Thread t1 = new Thread(my,"Plane");
Thread t2 = new Thread(my,"Train");
t1.start();
t2.start();
}
}
相比于继承Thread类,实现Runnable接口的好处:
- 避免了java单继承的局限性 即使用实现Runnable接口来实现多线程,类还可以继承它的父类
- 适合多个相同程序代码去处理同一个资源的情况,把线程和程序的代码、数据有效分离,较好的体现了Java面向对象的思想