Skip to content

Instantly share code, notes, and snippets.

@Sjm810
Created January 20, 2017 06:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sjm810/403520e7fc75feaf49f54f5b1ee0d29d to your computer and use it in GitHub Desktop.
Save Sjm810/403520e7fc75feaf49f54f5b1ee0d29d to your computer and use it in GitHub Desktop.
Java example of processing threads using concurrency
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