Javaの複数のスレッドでどのように順番にプリントするか
Java では、複数のスレッドを順次実行するためのさまざまな方法があります。
- 各スレッドの最後に前スレッドの`join()`メソッドを呼び出し、前スレッドの完了を待ってから次スレッドを実行するようにします。
Thread t1 = new Thread(() -> {
System.out.println("线程1");
});
Thread t2 = new Thread(() -> {
try {
t1.join();
System.out.println("线程2");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread t3 = new Thread(() -> {
try {
t2.join();
System.out.println("线程3");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t1.start();
t2.start();
t3.start();
- CountDownLatchを使用して:CountDownLatchは、1つまたは複数のスレッドが、一連の操作が完了するまで待機する際に使用するカウントダウン機能です。例:
CountDownLatch latch1 = new CountDownLatch(1);
CountDownLatch latch2 = new CountDownLatch(1);
Thread t1 = new Thread(() -> {
try {
latch1.await();
System.out.println("线程1");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
latch2.countDown();
}
});
Thread t2 = new Thread(() -> {
try {
latch2.await();
System.out.println("线程2");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread t3 = new Thread(() -> {
try {
latch2.await();
System.out.println("线程3");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t1.start();
t2.start();
t3.start();
latch1.countDown();
スレッドt2およびt3は、スレッドt1が実行を完了するまで待機します。
- ロックと条件変数を使う:ロックと条件変数を使用すると、CountDownLatchに似た機能を実装できます。例えば:
Lock lock = new ReentrantLock();
Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
Thread t1 = new Thread(() -> {
try {
lock.lock();
System.out.println("线程1");
condition2.signal();
} finally {
lock.unlock();
}
});
Thread t2 = new Thread(() -> {
try {
lock.lock();
condition2.await();
System.out.println("线程2");
condition1.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
});
Thread t3 = new Thread(() -> {
try {
lock.lock();
condition1.await();
System.out.println("线程3");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
});
t1.start();
t2.start();
t3.start();
スレッドt2、t3がスレッドt1の実行完了を待機する。
状況と要件に応じて、これらの方法のいずれでも指定した順序で複数のスレッドを出力できます。