Skip to content

Instantly share code, notes, and snippets.

/.java Secret

Created May 26, 2016 18:06
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 anonymous/ed2755b414ed1173e169a5f875e74d44 to your computer and use it in GitHub Desktop.
Save anonymous/ed2755b414ed1173e169a5f875e74d44 to your computer and use it in GitHub Desktop.
public class Worker {
Random random = new Random();
private List<Integer> list1 = new ArrayList<Integer>();
private List<Integer> list2 = new ArrayList<Integer>();
/*if we were to try to make this synchronized, it will work, however, it will take twice as long
* therefore, the second thread must wait for the same thread to finish before it can access these stages
*/
public synchronized void stageOne() throws InterruptedException {
Thread.sleep(1);
list1.add(random.nextInt(100));
}
public synchronized void stageTwo() throws InterruptedException {
Thread.sleep(1);
list2.add(random.nextInt(100));
}
public void process() {
try {
for (int i = 0; i < 1000; i++) {
stageOne();
stageTwo();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void main() {
System.out.println("Starting...");
long start = System.currentTimeMillis();
Thread thread=new Thread(new Runnable(){
@Override
public void run() {
process();
}
});
Thread thread1=new Thread(new Runnable(){
@Override
public void run() {
process();
}
});
//ArrayLists are not thread safe, therefore, they can interleave
thread.start();
thread1.start();
try {
thread.join();
thread1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
long finish = System.currentTimeMillis();
System.out.println("Time Taken " + (finish - start));
System.out.println("List 1 Size " + list1.size());
System.out.println("List 2 Size " + list2.size());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment