java编写程序,实现创建3个线程。 A) 分别输出1~10之间的数字及对应的输出数字线程名 B) 线程优先级分别为最高、普通、最低 C) 每个线程输出一次后,休眠一秒钟
时间: 2024-10-10 11:13:18 浏览: 29
java多线程实现有序输出ABC
在Java中,我们可以利用`Thread`, `Runnable`接口,以及`ExecutorService`来创建并管理线程。这里是一个简单的示例,实现了A) B) C)的需求:
```java
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadExample implements Runnable {
private int number;
private String threadName;
private int priority;
public ThreadExample(int num, String name, int pri) {
this.number = num;
this.threadName = name;
this.priority = pri;
}
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("线程名:" + threadName + " 数字:" + i);
try {
Thread.sleep(1000); // 休眠1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// 创建线程池,并设置线程优先级
ExecutorService executor = Executors.newFixedThreadPool(3, r -> {
Thread t = new Thread(r);
switch (r.getPriority()) {
case Thread.MIN_PRIORITY:
t.setPriority(Thread.MIN_PRIORITY);
break;
case Thread.NORM_PRIORITY:
t.setPriority(Thread.NORM_PRIORITY);
break;
case Thread.MAX_PRIORITY:
t.setPriority(Thread.MAX_PRIORITY);
break;
}
return t;
});
// 创建三个线程实例并加入线程池
ThreadExample thread1 = new ThreadExample(1, "HighPriority", Thread.MAX_PRIORITY);
ThreadExample thread2 = new ThreadExample(2, "NormalPriority", Thread.NORM_PRIORITY);
ThreadExample thread3 = new ThreadExample(3, "LowPriority", Thread.MIN_PRIORITY);
executor.execute(thread1);
executor.execute(thread2);
executor.execute(thread3);
// 关闭线程池
executor.shutdown();
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
```
在这个例子中,我们创建了三个`ThreadExample`实例,每个实例对应一个线程,通过`run()`方法打印数字和线程名称。我们设置了线程池,其中每个线程在提交给线程池时会自动按照设定的优先级运行。每个线程执行完1到10的循环后都会暂停1秒。
阅读全文