我有3个线程,我希望它按顺序打印,但是当我运行该程序时,它不断得到结果。我不明白它如何不能按顺序运行线程。我想继续分别运行线程1和2和3。在每个线程中都有一个用于多次打印的循环。所以我想让主线程按顺序运行每个线程。这是我的代码。如何使线程顺序工作并多次运行?
threadMessage("Starting MessageLoop thread");
long patience =
long startTime = System.currentTimeMillis();
Thread t = new Thread(new MessageLoop());
Thread t2 = new Thread(new MessageLoop2());
Thread t3 = new Thread(new MessageLoop3());
t.setPriority(10);
t2.setPriority(5);
t3.setPriority(1);
t.start();
t2.start();
t3.start();
这是我的线程函数(3个线程)
private static class MessageLoop
implements Runnable {
public void run() {
try {
for(int i = 0;i<20;i++)
{
Thread.sleep(1000);
// Print a message
threadMessage("A");
}
} catch (InterruptedException e) {
threadMessage("thread interrupted");
}
}
}
private static class MessageLoop2
implements Runnable {
public void run() {
try {
for(int i = 0;i<20;i++)
{ Thread.sleep(1000);
// Print a message
threadMessage("B");
}
} catch (InterruptedException e) {
threadMessage("thread interrupted");
}
}
private static class MessageLoop3
implements Runnable {
public void run() {
String importantInfo = "E";
try {
for(int i = 0;i<20;i++)
{
Thread.sleep(1000);
// Print a message
threadMessage(importantInfo);
}
} catch (InterruptedException e) {
threadMessage("Thread interrupted");
}
}
这是我的代码,使其在顺序运行。我想让我的程序按照这个MessageLoop1和2和3的顺序运行。
while (t.isAlive()) {
threadMessage("Still waiting...");
t.join(2000);
if (((System.currentTimeMillis() - startTime) > patience)
&& t.isAlive()) {
threadMessage("Tired of waiting!");
t.interrupt();
// Shouldn't be long now
// -- wait indefinitely
t.join();
}
while(t2.isAlive()){
threadMessage("Still waiting...");
t2.join(1000);
if (((System.currentTimeMillis() - startTime) > patience)
&& t2.isAlive()) {
threadMessage("Tired of waiting!");
t2.interrupt();
// Shouldn't be long now
// -- wait indefinitely
t2.join();
}
}
while(t3.isAlive()){
threadMessage("Still waiting...");
t3.join(1000);
if (((System.currentTimeMillis() - startTime) > patience)
&& t3.isAlive()) {
threadMessage("Tired of waiting!");
t3.interrupt();
// Shouldn't be long now
// -- wait indefinitely
t3.join();
}
}
}
但结果快到像B,A,C。有谁能解释这种情况吗?我的代码错了吗?谢谢!
您不控制订单;操作系统呢。如果订单很重要,那么它们不应该在单独的线程中。 – duffymo