いくつかのコードを共有するとうれしいでしょう。論理を見ずにコードをデバッグするのは難しいです。スレッド1とスレッド2は独立して動作するのが理想的です。スレッド2はスレッド1のループで終了するのを待つことができません。 例:
class RunnableDemo implements Runnable {
private Thread t;
private String threadName;
RunnableDemo(String name){
threadName = name;
System.out.println("Creating " + threadName);
}
public void run() {
System.out.println("Running " + threadName);
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start()
{
System.out.println("Starting " + threadName);
if (t == null)
{
t = new Thread (this, threadName);
t.start();
}
}
}
public class TestThread {
public static void main(String args[]) {
RunnableDemo R1 = new RunnableDemo("Thread-1");
R1.start();
RunnableDemo R2 = new RunnableDemo("Thread-2");
R2.start();
}
}
出力:
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
あなたのアプリケーションは、それが適用されません任意の実行順序の制約に依存するべきではありません。それは? –
'Thread#yield()'を使ってみることもできますが、必要ないときにはそれを使用することはお勧めできません。両方のスレッドを同時に実行させることは本当に重要ですか?そして、もしそうなら、彼らは何をしていますか、そして彼らの間ではどのような同期/メッセージングが起こっていますか?あなたの説明はスレッド1が優先度の低いバックグラウンドスレッドであるかもしれないのに対し、スレッド2はより高い優先度を持つべきであるので、 'Thead#setPriority()'を使ってみてください。 – Thomas
これはスレッドを持つものです。あなたはそこで多くのコントロールを持っていません。その意味では、あなたは既に**測定**を始めたようです。だから、あなたは一歩進んで、睡眠を加えることが物事を変える方法を見て実験を始めるべきです。その後、java 1.4;真剣に?あなたは、Oracleがjavaバージョンの「end of life」の日付を追跡している表に、バージョンがもはやリストされていないことを知っています。 – GhostCat