私は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