线程的两种实现⽅式多线程的两种实现⽅式
第⼀种⽅式:
1.创建个类继承Thread;
2.在类⾥重写run⽅法,在⽅法⾥编写你需要的逻辑;开凯迪拉克追高铁
3.创建类对象
4.调⽤start()⽅法,启动线程.
public class TextThread1 {
public static void main(String[] args){
//创建类对象
thread youthread =new thread();
thread1 youthread1 =new thread1();
/
/调⽤start()⽅法,启动线程
youthread.start();
youthread1.start();
}
}
//创建⼀个类thread继承Thread,
class thread extends Thread{
//重写run⽅法
@Override
public void run(){
for(int i =1; i <=100; i++){
System.out.println("360⽂件读取速度为:"+i+"%");
}
}
}
//创建⼀个类thread1继承Thread
class thread1 extends Thread{
//重写run⽅法
@Override
public void run(){
for(int i =0; i <=100; i++){
System.out.println("王者荣耀⽂件下载速度:"+i+"%");
}
}
}
第⼆种⽅式(实现Runnable接⼝):
1.定义⼀个类实现Runnable接⼝;
2.在类中重写run()⽅法;
3.创建实现类的对象;
4.创建Thread类的对象,把实现类对象作为构造⽅法的参数;
5.调⽤start()⽅法,启动线程.
public class TextRunnable {
public static void main(String[] args){
System.out.println("凯迪拉克追爱情:");
//创建task类的对象
task taskOne =new task();
//创建Thread类的对象,把task对象作为构造⽅法的参数,后⾯是线程名称
Thread thread =new Thread(taskOne,"男孩驾驶的凯迪拉克");
Thread thread1 =new Thread(taskOne,"⼥孩乘坐的⾼铁");
//启动线程
thread.start();
thread1.start();
}
}
/
/定义⼀个类task实现Runnab1e接⼝
class task implements Runnable{
//重写run()⽅法
@Override
public void run(){
for(int i =0; i <=100; i++){
//调⽤Thread类的currentThread()⽅法是返回线程名称
System.out.println(Thread.currentThread().getName()+"⾏驶了"+ i +"公⾥");
}
}
}