【发布时间】:2021-08-21 13:36:58
【问题描述】:
我是 Java 多线程的新手,并试图找出创建 3 个线程 a、b 和 c 的以下代码的输出。
class A extends Thread {
int i = 0;
public void run() {
System.out.println("Thread A started");
while (i < 4) {
System.out.println("\t value of i in Thread A:" + i);
i++;
}
System.out.println("ThreadA finished");
}
}
class B extends Thread {
public void run() {
int i = 0;
System.out.println("ThreadB started");
while (i < 4) {
System.out.println("\t value of i in Thread B:" + i);
i++;
}
System.out.println("ThreadB finished");
}
}
class C extends Thread {
public void run() {
int i = 0;
System.out.println("ThreadC started");
while (i < 4) {
System.out.println("\t value of i in Thread C" + i);
i++;
}
System.out.println("ThreadC finished");
}
}
public class App {
public static void main(String[] args) throws Exception {
// System.out.println("Hello, World!");
System.out.println("Main Thread started");
A a = new A();
B b = new B();
C c = new C();
Thread th = Thread.currentThread();
System.out.println(th.getName());
System.out.println(th.getPriority());
System.out.println("Priority of A thread " + a.getPriority());
System.out.println("Priority of B thread " + b.getPriority());
System.out.println("Priority of C thread " + c.getPriority());
System.out.println();
th.setPriority(Thread.MAX_PRIORITY);
b.setPriority(Thread.MIN_PRIORITY);
c.setPriority(Thread.NORM_PRIORITY);
System.out.println("Showing new Priorites \n");
System.out.println("Priority of TH thread " + th.getPriority());
System.out.println("Priority of A thread " + a.getPriority());
System.out.println("Priority of B thread " + b.getPriority());
System.out.println("Priority of C thread " + c.getPriority());
System.out.println();
a.start();
b.start();
c.start();
}
}
以上代码的输出是
Main Thread started
main
5
Priority of A thread 5
Priority of B thread 5
Priority of C thread 5
Showing new Priorites
Priority of TH thread 10
Priority of A thread 5
Priority of B thread 1
Priority of C thread 5
ThreadC started
value of i in Thread C0
Thread A started
value of i in Thread A:0
value of i in Thread A:1
value of i in Thread C1
value of i in Thread C2
value of i in Thread C3
ThreadC finished
ThreadB started
value of i in Thread A:2
value of i in Thread A:3
ThreadA finished
value of i in Thread B:0
value of i in Thread B:1
value of i in Thread B:2
value of i in Thread B:3
ThreadB finished
我知道在调用 start() 方法后,线程变得可运行并准备好被线程调度程序选择。
从输出中我们可以看到线程 C 首先开始运行它的 run() 方法,然后它应该已经完成了它的 run() 方法。但是在线程 C 的 run() 方法完成之前,线程 a 的 run() 方法是如何执行的呢? 有人请在这里帮忙。
【问题讨论】:
-
在某些系统上,
A、B和C可能同时运行。这通常是多线程的point。如果一切都是串行执行的,为什么还需要多个执行线程? -
嗨@ElliottFrisch,您的回复。这就是为什么我在不同的机器上得到不同的输出。
-
顺便说一下,在现代 Java 中,我们很少需要直接寻址
Thread类。我们使用 Executors 框架来抽象出线程和线程池。
标签: java multithreading threadpool