Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package multithread;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Worker implements Runnable {
public boolean running = false;
public Worker() {
Thread thread = new Thread();
System.out.println("In constructor now, ID = " + Thread.currentThread().getId());
thread.start();
thread.run();
System.out.println("Finished run().");
}
public static void main(String... args) throws InterruptedException {
List<Worker> workers = new ArrayList<>();
System.out.println("Main thread is running with thread ID: " + Thread.currentThread().getId());
Date start = new Date();
//let's start 10 workers
for (int i = 0; i < 10; i++){
System.out.println("i = " + i);
workers.add(new Worker());
}
//now we need to force the MAIN thread to wait until all Worker threads end, so we could calculate the duration
for (Worker worker : workers){
System.out.println("Checking thread " + Thread.currentThread().getId() + " now.");
System.out.println("worker.running = " + worker.running);
while (worker.running){
Thread.sleep(1000);
}
}
Date end = new Date();
Long duration = end.getTime() - start.getTime();
System.out.println("This whole process took " + duration/1000 + " seconds.");
}
@Override
public void run() {
this.running = true;
System.out.println("Thread " + Thread.currentThread().getId() + " is running.");
try {
//this pauses this spawned thread to sleep for 5 seconds.
Thread.sleep(5000);
} catch (InterruptedException e) {
//an InterruptedException should never be swallowed
Thread.currentThread().interrupt();
}
this.running = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.