...
Code Block | ||
---|---|---|
| ||
public class ProcessStep implements Runnable {
private static final Object lock = new Object();
private static int time = 1;
private final int step; // Do operations when the step reaches this value
public ProcessStep(int step) {
this.step = step;
}
public void run() {
try {
synchronized (lock) {
while (time != step) {
lock.wait();
}
// ... Do operations
time++;
lock.notify();
}
} catch (InterruptedException ie) {
Thread.currentThread().interrupt(); // Reset interrupted status
}
}
public static void main(String[] args) {
for (int i = 5; i > 0; i--) {
ProcessStep ms = new ProcessStep(i);
new Thread(ms).start();
}
}
}
|
...
Code Block | ||
---|---|---|
| ||
public class ProcessStep implements Runnable {
private static final Lock lock = new ReentrantLock();
private static final Condition condition = lock.newCondition();
private static int time = 1;
private final int step; // Do operations when the step reaches this value
public ProcessStep(int step) {
this.step = step;
}
public void run() {
lock.lock();
try {
while (time != step) {
condition.await();
}
// ... Do operations
time++;
condition.signal();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt(); // Reset interrupted status
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
for (int i = 5; i > 0; i--) {
ProcessStep ms = new ProcessStep(i);
new Thread(ms).start();
}
}
}
|
...
Code Block | ||
---|---|---|
| ||
public class ProcessStep implements Runnable { private static final Lock lock = new ReentrantLock(); private static int time = 1; private final int step; // Do operations when the step reaches this value private static final Condition[] conditions = new Condition[step6]; public ProcessStep(int step) { this.step = step; conditions[step] = lock.newCondition(); } public void run() { lock.lock(); try { while (time != step) { conditions[step].await(); } // ... Do operations time++; if (step + 1 < conditions.length) { conditions[step + 1].signal(); } } catch (InterruptedException ie) { Thread.currentThread().interrupt(); // Reset interrupted status } finally { lock.unlock(); } } public static void main(String[] args) { for (int i = 5; i > 0; i--) { ProcessStep ms = new ProcessStep(i); new Thread(ms).start(); } } } |
...