Created
January 30, 2017 03:41
Star
You must be signed in to star a gist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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