java 创建10个线程
时间: 2023-11-15 08:04:10 浏览: 52
下面是一个简单的 Java 代码示例,可以创建 10 个线程:
```java
public class MyThread implements Runnable {
private int threadNumber;
public MyThread(int threadNumber) {
this.threadNumber = threadNumber;
}
public void run() {
System.out.println("Thread " + threadNumber + " is running.");
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(new MyThread(i));
thread.start();
}
}
}
```
在上述示例中,我们通过实现 `Runnable` 接口来创建线程类 `MyThread`,并在 `run()` 方法中编写线程的主要逻辑。在 `main()` 方法中,我们使用 `for` 循环创建 10 个线程,并启动它们。每个线程都会运行 `run()` 方法中的代码,输出线程编号。
注意,线程启动后,它们的运行顺序是不确定的,可能会交替运行或并行运行。因此,在编写多线程程序时,需要特别注意线程安全问题。