Skip to content

Instantly share code, notes, and snippets.

@finkformatics
Created April 9, 2016 08:20
Show Gist options
  • Save finkformatics/c1a53b8b03fe4d93e1e9dfcfc50c9cb5 to your computer and use it in GitHub Desktop.
Save finkformatics/c1a53b8b03fe4d93e1e9dfcfc50c9cb5 to your computer and use it in GitHub Desktop.
Simple Thread example
/**
* Simple thread example
*
* Creates a certain number of threads and lets each thread print out a message and its index in the array.
*
* Result: The outputs aren't in the order the threads were created.
*/
public class ThreadExample {
public static void main(String[] args) {
// Create array of 8 threads
Thread[] threads = new Thread[8];
for (int i = 0; i < threads.length; i++) {
// Create final variable to use in anonymous inner class
final int count = i;
threads[i] = new Thread(() -> {
// Say hello
System.out.println("Hello World from Thread " + count);
});
// Start the thread
threads[i].start();
}
// Unnecessary here, but good to know: Waits for each thread to finish work
for (Thread t: threads) {
try {
t.join();
} catch (InterruptedException e) { }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment