Created
April 9, 2016 08:20
-
-
Save finkformatics/c1a53b8b03fe4d93e1e9dfcfc50c9cb5 to your computer and use it in GitHub Desktop.
Simple Thread example
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
/** | |
* 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