实现线程的两种方式
1、继承方式实现:
继承Thread类,重写run方法;
在执行时,不能直接执行调用run方法,直接调用run的方法时,不会生成新线程;
而如果要开启新线程,而是需要调用star方法,才会生成新的线程
启动线程的唯一方法就是通过Thread类的start()实例方法。start()方法是一个native方法,它将启动一个新线程,并执行run()方法。这种方式实现多线程很简单,
步骤:继承Thread类
1、定义一个类MyThread继承Thread类
2、在MyThread类中去重写run()方法
3、创建MyThread类对象
4、启动线程
1、定义一个类MyThread继承Thread类
2、在MyThread类中去重写run()方法
package duoxiancheng;
public class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println(Thread.currentThread().getName());
System.out.println(i);
}
}
}
3、创建MyThread类对象
4、启动线程
package duoxiancheng;
import java.util.Iterator;
public class ThreadCmj {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
MyThread my1=new MyThread();
MyThread my2=new MyThread();
my1.setName("张飞");
my2.setName("关于");
my1.start();
my2.start();
}
}
可以通过my1.setName("张飞");设置该线程名称
my1.star()启动线程
2、通过接口方式实现线程
1、定义一个类MyRunnable实现Runnable接口
2、在MyRunnable类中去重写run()方法
3、创建MyRunnable类对象
4、把对象通过参数形式注入到Thead中
5、启动线程
1、定义一个类MyRunnable实现Runnable接口
2、在MyRunnable类中去重写run()方法
package duoxiancheng;
public class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
3、创建MyRunnable类对象
4、把对象通过参数形式注入到Thead中
5、启动线程
package duoxiancheng;
public class MyRunnableDemo {
public static void main(String[] args) {
//创建MyRunnable对象
MyRunnable my =new MyRunnable();
Thread t1=new Thread(my,"飞机"); //将myRunnable作为Thread target创建新的线程,后面可以直接设置线程名称
Thread t2=new Thread(my,"火车");
Thread t3=new Thread(()->{
System.out.println(Thread.currentThread().getName()+":t3");
},"RTATT");//或者直接通过这种方式,将不需要创建MyRunnable对象,直接通过这种方式创建线程
t1.start();
t2.start();
t3.start();
}
}
3、匿名类的实现方式
1、定义一个类MyRunnable实现Runnable接口
2、在MyRunnable类中去重写run()方法
3、以匿名方式实现
package duoxiancheng;
public class MyRunnableDemo {
public static void main(String[] args) {
//创建MyRunnable对象
MyRunnable my =new MyRunnable();
Thread t1=new Thread(my,"飞机"); //将myRunnable作为Thread target创建新的线程,后面可以直接设置线程名称
Thread t2=new Thread(my,"火车");
Thread t3=new Thread(()->{
System.out.println(Thread.currentThread().getName()+":t3");
},"RTATT");//或者直接通过这种方式,将不需要创建MyRunnable对象,直接通过这种方式创建线程
t1.start();
t2.start();
t3.start();
}
}
System.out.println(Thread.currentThread().getName()+":t3");
},"RTATT");
//或者直接通过这种方式,将不需要创建MyRunnable对象,直接通过这种方式创建线程
"RTATT"为创建的该线程的名称:
4、设置和获取线程名称:
Thread类中设置和获取线程名称的方法:
①、void setName(string name)将此线程的名称更改为等于参数name的名称![](https://img-blog.csdnimg.cn/0e7c2c2ef9cc4277ba3ad93b08f31943.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA6JCd5Y2c6Zi_5ZKV5ZKV,size_17,color_FFFFFF,t_70,g_se,x_16)
②、String getName():返回此线程的名称
一般使用:Thread.currentThread().getName():获取当前进程名称
③、通过构造方法也可以设置
通过有参构造方法进行传入对应线程名字: