创建多线程
继承Thread类,并重写run方法
public class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
// getName: 获取线程的名称
System.out.println(getName() + " --- " + i);
}
}
}
测试通过继承创建线程
public static void main(String[] args) throws Exception {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
// 通过start来启动线程
t1.start();
t2.start();
t3.start();
// 可以通过setName给线程添加名称
t1.setName("线程1");
}
可以通过实现Runnable接口来创建多线程
public class MyRunnable implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
// 可以通过Thread的currentThread()方法来获取当前线程
//再通过当前线程来调用getName来获取线程名称
System.out.println(Thread.currentThread().getName() + " --- " + i);
}
}
}
测试通过实现接口创建线程
main方法
```java
public static void main(String[] args) throws Exception {
MyRunnable r1 = new MyRunnable();
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r1);
Thread t3 = new Thread(r1);
t1.start();
t2.start();
t3.start();
}
Runnable接口是一个函数式接口,我们还可以通过lambda表达式来实现
public static void main(String[] args) throws Exception {
new Thread(() -> {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " --- " + i);
}
}).start();
}