定义类实现Thread或实现Runnable接口。示例代码如下:
import java.util.Random;
public class MultiThread {
public static void main(String args[]) throws InterruptedException {
System.out.println("使用继承Thread的方式实现");
for (int i = 0; i < 10; i++) {
MyThread t = new MyThread("thread_" + i);
t.start();
}
Thread.sleep(1000);
System.out.println("使用实现Runnable接口的方式实现");
for (int i = 10; i < 20; i++) {
MyThread2 t = new MyThread2("thread_" + i);
new Thread(t).start();
}
}
}
class MyThread extends Thread {
private String threadName;
public MyThread(String threadName) {
this.threadName = threadName;
}
@Override
public void run() {
long sleep = new Random().nextInt(100) + 100;
try {
// 随机延迟一段时间
Thread.sleep(sleep);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(threadName + " 开始执行...");
}
}
class MyThread2 implements Runnable {
private String threadName;
public MyThread2(String threadName) {
this.threadName = threadName;
}
@Override
public void run() {
long sleep = new Random().nextInt(100) + 100;
try {
// 随机延迟一段时间
Thread.sleep(sleep);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(threadName + " 开始执行...");
}
}