I made this studying my Java book about concurrency. It's just to test. I feel it works ok but I'm not so sure about my Java. I worry maybe my code style is strange. I really didn't want that exception. It bothers me that I have to catch it.
I'd love to hear your input on the Java style used here. Any suggestion for how to do something better is welcome! Is it ok to make the array of threads like this?
package com.katie;
// Demonstration of a counter that is not thread-safe.
class Counter {
private int myCounter = 0;
public void increment() { myCounter++; }
public int getCounter() { return myCounter; }
}
class BadIdea implements Runnable {
private Counter myTarget;
private int myStabs;
BadIdea(Counter victim, int stabs) {
myTarget = victim;
myStabs = stabs;
}
public void run() {
for (int i = 0; i < myStabs; i++) {
myTarget.increment();
}
}
}
public class Main {
public static void main(String[] args) {
Counter guineaPig = new Counter();
final int stabCount = 1000;
final int threadCount = 3;
// make multiple threads and use them to break the guineaPig
// because she is not thread safe!
Thread[] threads = new Thread[threadCount];
for (int i = 0; i < threadCount; i++) {
threads[i] = new Thread(new BadIdea(guineaPig, stabCount));
}
for (Thread t : threads) {
t.start();
}
for (Thread t : threads) {
try {
t.join();
} catch (InterruptedException e) {
// i dont care!!
}
}
// These will be different sometimes.
System.out.println(guineaPig.getCounter());
System.out.println(threadCount * stabCount);
}
}