Skip to content

Instantly share code, notes, and snippets.

@fishercoder1534
Created January 30, 2017 03:41
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save fishercoder1534/143c2603de7aeb70cda6b221f8db3a4a to your computer and use it in GitHub Desktop.
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