Поэтому у меня есть этот код
class PrintDemo {
public void printCount(){
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter --- " + i );
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
}
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
PrintDemo PD;
ThreadDemo( String name, PrintDemo pd){
threadName = name;
PD = pd;
}
public void run() {
synchronized(PD) {
PD.printCount();
}
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[]) {
PrintDemo PD = new PrintDemo();
ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );
ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );
T1.start();
T2.start();
// wait for threads to end
try {
T1.join();
T2.join();
} catch( Exception e) {
System.out.println("Interrupted");
}
И это печатает следующий результат:
Starting Thread - 1
Starting Thread - 2
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 1 exiting.
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 2 exiting.
Есть ли способ, с помощью которого можно уменьшить поток 1 на один, а затем поток 2 на один, пока оба не равны 1, вместо того, чтобы просто уменьшить поток 1 до 1, а затем поток 2 уменьшится до 1.
Поскольку вы используете один и тот же объект класса PrintDemo
в обоих потоках, который можно использовать как блокировку (монитор).
образец кода:
class PrintDemo {
public void printCount() {
try {
for (int i = 5; i > 0; i--) {
synchronized (this) {
this.notify();
}
System.out.println(Thread.currentThread().getName()+" Counter --- " + i);
synchronized (this) {
this.wait();
}
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
}
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
PrintDemo PD;
ThreadDemo(String name, PrintDemo pd) {
threadName = name;
PD = pd;
}
public void run() {
synchronized (PD) {
PD.printCount();
}
System.out.println("Thread " + threadName + " exiting.");
synchronized (PD) {
PD.notify(); // notify the last waited thread.
}
}
public void start() {
System.out.println("Starting " + threadName);
if (t == null) {
t = new Thread(this, threadName);
t.start();
}
}
}
вывод:
Starting Thread - 1
Starting Thread - 2
Thread - 1 Counter --- 5
Thread - 2 Counter --- 5
Thread - 1 Counter --- 4
Thread - 2 Counter --- 4
Thread - 1 Counter --- 3
Thread - 2 Counter --- 3
Thread - 1 Counter --- 2
Thread - 2 Counter --- 2
Thread - 1 Counter --- 1
Thread - 2 Counter --- 1
Thread Thread - 1 exiting.
Thread Thread - 2 exiting.
Визуальное представление:
wait
иnotify