Java多线程
Java有三种方式实现多线程:
- Thread类(重点)
- Runnable接口(重点)
- Callable接口(了解)
实现步骤:
Thread类
①创建子类继承Thread类
②重写Thread类的run方法
③在主线程中 start() 启动线程
Runnable接口
①创建Runnable的实现类A
②在A中重写 run() 方法
③主线程中创建A的实例对象
④使用Thread类的传参构造方法,传入A的示例对象与线程名
格式: Thread thread = new Thread(A ,“name”) ;
⑤主线程中 start() 启动线程
示例代码
package Thread_Experiments;
public class Thread_Test {
public static void main(String[] args) {
MyThread thread1 =new MyThread("线程1"); //实例化Mythread类
MyRunnnable a = new MyRunnnable(); //实例化Runnable的实现类
Thread thread2 = new Thread( a,"线程2"); //Thread传参构造方法, 传入Runnable的实现类的对象与线程名
thread1.start(); //启动线程
thread2.start();
System.out.println(System.currentTimeMillis()+"毫秒,"+"主线程已经结束");
//使用System.currentTimeMillis()来获取系统时间,记录线程执行时间
}
}
class MyThread extends Thread{//继承Thread类
public MyThread(String name){
super(name);//引用父类构造方法
}
@Override
public void run(){
for (int i = 0; i < 10; i++) {
System.out.println(System.currentTimeMillis()+"毫秒,"+Thread.currentThread().getName() +"正在运行");
}
}
}
class MyRunnnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(System.currentTimeMillis() + "毫秒," + Thread.currentThread().getName() + "正在运行");
}
}
}
输出结果:
1637158974435毫秒,主线程已经结束
1637158974435毫秒,线程1正在运行
1637158974457毫秒,线程1正在运行
1637158974435毫秒,线程2正在运行
1637158974457毫秒,线程2正在运行
1637158974457毫秒,线程1正在运行
1637158974457毫秒,线程1正在运行
1637158974457毫秒,线程2正在运行
1637158974457毫秒,线程1正在运行
1637158974457毫秒,线程2正在运行
1637158974457毫秒,线程2正在运行
1637158974457毫秒,线程1正在运行
1637158974457毫秒,线程2正在运行
1637158974457毫秒,线程2正在运行
1637158974457毫秒,线程2正在运行
1637158974457毫秒,线程1正在运行
1637158974458毫秒,线程2正在运行
1637158974458毫秒,线程2正在运行
1637158974458毫秒,线程1正在运行
1637158974458毫秒,线程1正在运行
1637158974458毫秒,线程1正在运行