Checkpoint synchronization: Difference between revisions

→‎{{header|Java}}: Added Java 5 version
(→‎{{header|Go}}: serialized output)
(→‎{{header|Java}}: Added Java 5 version)
Line 454:
 
=={{header|Java}}==
<lang Java>import java.util.Scanner;
 
<lang Java>
import java.util.Scanner;
import java.util.Random;
 
Line 583 ⟶ 581:
Worker 2 is ready
</pre>
{{works with|Java|1.5+}}
<lang java5>import java.util.Random;
import java.util.concurrent.CountDownLatch;
 
public class Sync {
static class Worker implements Runnable {
private final CountDownLatch doneSignal;
private int threadID;
 
public Worker(int id, CountDownLatch doneSignal) {
this.doneSignal = doneSignal;
threadID = id;
}
 
public void run() {
doWork();
doneSignal.countDown();
}
 
void doWork() {
try {
int workTime = new Random().nextInt(900) + 100;
System.out.println("Worker " + threadID + " will work for " + workTime + " msec.");
Thread.sleep(workTime); //work for 'workTime'
System.out.println("Worker " + threadID + " is ready");
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
}
 
public static void main(String[] args) {
int n = 3;//6 workers and 3 tasks
for(int task = 1; task <= n; task++) {
CountDownLatch latch = new CountDownLatch(n * 2);
System.out.println("Starting task " + task);
for(int worker = 0; worker < n * 2; worker++) {
new Thread(new Worker(worker, latch)).start();
}
try {
latch.await();//wait for n*2 threads to signal the latch
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Task " + task + " complete");
}
}
}</lang Java>
Output:
<pre style="height: 200px;overflow:scroll">Starting task 1
Worker 0 will work for 959 msec.
Worker 1 will work for 905 msec.
Worker 3 will work for 622 msec.
Worker 2 will work for 969 msec.
Worker 4 will work for 577 msec.
Worker 5 will work for 727 msec.
Worker 4 is ready
Worker 3 is ready
Worker 5 is ready
Worker 1 is ready
Worker 0 is ready
Worker 2 is ready
Task 1 complete
Starting task 2
Worker 0 will work for 305 msec.
Worker 2 will work for 541 msec.
Worker 4 will work for 663 msec.
Worker 1 will work for 883 msec.
Worker 3 will work for 324 msec.
Worker 5 will work for 459 msec.
Worker 0 is ready
Worker 3 is ready
Worker 5 is ready
Worker 2 is ready
Worker 4 is ready
Worker 1 is ready
Task 2 complete
Starting task 3
Worker 0 will work for 554 msec.
Worker 2 will work for 727 msec.
Worker 1 will work for 203 msec.
Worker 4 will work for 249 msec.
Worker 3 will work for 612 msec.
Worker 5 will work for 723 msec.
Worker 1 is ready
Worker 4 is ready
Worker 0 is ready
Worker 3 is ready
Worker 5 is ready
Worker 2 is ready
Task 3 complete</pre>
 
=={{header|Perl}}==
Anonymous user