编写一个Java程序(包括一个主程序类,一个Thread类的子类)。在主程序中创建2个线程(用子类) ,将其中一个线程的优先级设为10,另一个线程的优先级设为6。
时间: 2024-04-30 20:23:52 浏览: 62
主程序类:
```java
public class Main {
public static void main(String[] args) {
MyThread thread1 = new MyThread("Thread 1");
MyThread thread2 = new MyThread("Thread 2");
thread1.setPriority(10);
thread2.setPriority(6);
thread1.start();
thread2.start();
}
}
```
Thread类的子类:
```java
public class MyThread extends Thread {
public MyThread(String name) {
super(name);
}
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println(getName() + ": " + i);
try {
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
输出:
```
Thread 1: 1
Thread 2: 1
Thread 1: 2
Thread 2: 2
Thread 1: 3
Thread 2: 3
Thread 1: 4
Thread 2: 4
Thread 1: 5
Thread 2: 5
Thread 1: 6
Thread 2: 6
Thread 1: 7
Thread 2: 7
Thread 1: 8
Thread 2: 8
Thread 1: 9
Thread 2: 9
Thread 1: 10
Thread 2: 10
```
阅读全文