对两种多线程的对比:
// Runnable 就是一个接口,Thread类实现了Runnable,Runnable存在解决只能单继承Thread的问题。
//因为Thread也实现了Runnable接口 且Runnable接口中只存在一个Run方法
// 因此,无论是implements Runnable还是 extendsThread都要实现run方法
// 只是如果是直接继承Thread类,当我们调用多线程的时候可以直接.start()
// 如果是通过实现Runnable接口,那么需要实例化Thread类来调用.start()
// Runnable 接口更适合于多个线程处理统一资源
1、直接继承Thread类
package com.temp;
/**
* @Author lanxiaofang
* @email 983770299@qq.com
* @date 2020/12/5 13:08
*/
public class P205_07_Thead{
public static void main(String[] args) {
TestThread testThread1 = new TestThread("1");
TestThread testThread2 = new TestThread("2");
testThread1.start();
testThread2.start();
System.out.println("main is ending");
}
}
class TestThread extends Thread{
private String name;
public TestThread(String name){
this.name = name;
}
@Override
public void run() {
for (int i = 0;i<5;i++){
try {
sleep((int)(1000*Math.random()));
} catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
System.out.println(interruptedException);
}
System.out.println(name + " is Running "+i);
}
}
}
2、实现Runnable接口
package com.temp;
/**
* @Author lanxiaofang
* @email 983770299@qq.com
* @date 2020/12/5 14:35
*/
public class P207_08_Runnablr {
public static void main(String[] args) {
TestThread2 testThread2 = new TestThread2("testThread2");
TestThread2 testThread21 = new TestThread2("testThread21");
Thread thread1 = new Thread(testThread2);
Thread thread2 = new Thread(testThread21);
thread1.start();
thread2.start();
}
}
class TestThread2 implements Runnable{
private String name;
public TestThread2(String name){
this.name = name;
}
@Override
public void run() {
for (int i=0;i<5;i++){
try {
Thread.sleep((int)(1000*Math.random()));
} catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
System.out.println(interruptedException);
}
System.out.println(name+" is running "+i);
}
}
}