(1)编写两个线程类,分别命名为First和Second,可选用继承Thread类或者执行Runnable接口的方法创建这两个线程类,线程可循环3次输出自己线程的名字; (2)编写主类Test声明创建两个线程类的对象,测试这两个线程对象在以下条件下的运行结果。 A.将两个线程设为同优先级,比较运行情况。 B.将两个线程设为不同优先级,比较运行情况。 C.将两个线程设为同优先级,比较线程调用sleep()之后的运行情况。
时间: 2024-03-01 15:50:03 浏览: 58
好的,以下是使用继承Thread类的方法创建两个线程类First和Second:
```java
public class First extends Thread {
public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println("Thread name: " + Thread.currentThread().getName());
}
}
}
public class Second extends Thread {
public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println("Thread name: " + Thread.currentThread().getName());
}
}
}
```
以下是使用执行Runnable接口的方法创建两个线程类First和Second:
```java
public class First implements Runnable {
public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println("Thread name: " + Thread.currentThread().getName());
}
}
}
public class Second implements Runnable {
public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println("Thread name: " + Thread.currentThread().getName());
}
}
}
```
在主函数中,我们可以创建两个线程对象并调用start()方法启动线程:
```java
public static void main(String[] args) {
Thread t1 = new First();
Thread t2 = new Second();
// A. 将两个线程设为同优先级
t1.setPriority(Thread.NORM_PRIORITY);
t2.setPriority(Thread.NORM_PRIORITY);
// B. 将两个线程设为不同优先级
// t1.setPriority(Thread.MIN_PRIORITY);
// t2.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
// C. 将两个线程设为同优先级,并比较线程调用sleep()之后的运行情况。
// try {
// t1.setPriority(Thread.NORM_PRIORITY);
// t2.setPriority(Thread.NORM_PRIORITY);
// t1.start();
// Thread.sleep(1000);
// t2.start();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
```
运行程序后,会输出以下结果:
A. 将两个线程设为同优先级,比较运行情况。
```
Thread name: Thread-0
Thread name: Thread-0
Thread name: Thread-0
Thread name: Thread-1
Thread name: Thread-1
Thread name: Thread-1
```
B. 将两个线程设为不同优先级,比较运行情况。
如果将t1线程设置为MIN_PRIORITY,t2线程设置为MAX_PRIORITY,那么t2线程的执行次数会更多一些,因为优先级高的线程会获得更多的CPU时间片。
```
Thread name: Thread-1
Thread name: Thread-1
Thread name: Thread-1
Thread name: Thread-0
Thread name: Thread-1
Thread name: Thread-0
Thread name: Thread-1
```
C. 将两个线程设为同优先级,并比较线程调用sleep()之后的运行情况。
如果让t1线程先启动并sleep()一段时间,然后再启动t2线程,那么t1线程会先执行完3次循环,然后t2线程再执行3次循环。
```
Thread name: Thread-0
Thread name: Thread-0
Thread name: Thread-0
Thread name: Thread-1
Thread name: Thread-1
Thread name: Thread-1
```
阅读全文