Created
January 20, 2017 06:55
-
-
Save Sjm810/403520e7fc75feaf49f54f5b1ee0d29d to your computer and use it in GitHub Desktop.
Java example of processing threads using concurrency
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 javaconcurrency; | |
import java.util.concurrent.atomic.AtomicInteger; | |
/** | |
* @author Steven McCormick | |
* | |
*/ | |
public class JavaConcurrency { | |
/** | |
* @param args the command line arguments | |
* @throws java.lang.InterruptedException | |
*/ | |
public static void main(String[] args) throws InterruptedException { | |
ProcessingThreads pt = new ProcessingThreads(); | |
Thread t1 = new Thread(pt, "Thread1"); | |
t1.start(); | |
Thread t2 = new Thread(pt, "Thread2"); | |
t2.start(); | |
t1.join(); | |
t2.join(); | |
System.out.println("Processing count=" + pt.getCount()); | |
} | |
} | |
class ProcessingThreads implements Runnable { | |
private final AtomicInteger count = new AtomicInteger(); | |
@Override | |
public void run() { | |
for (int i = 1; i < 3; i++) { | |
processThreads(i); | |
count.incrementAndGet(); | |
} | |
} | |
public int getCount() { | |
return this.count.get(); | |
} | |
private void processThreads(int i) { | |
// processing threads...this statement will repeat | |
// until the wait time has been reached. | |
System.out.println("Processing...Please Wait..."); | |
try { | |
Thread.sleep(i * 500); | |
} catch (InterruptedException e) { | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment