public class Counter_ThreadSafe {
public int getCount(){
return _count;
}
public synchronized void count(){
++_count;
}
private volatile int _count=0;
}
public int getCount(){
return _count;
}
public synchronized void count(){
++_count;
}
private volatile int _count=0;
public static void main(String[] args) throws InterruptedException {
final Counter_ThreadSafe c = new Counter_ThreadSafe();
final Random rand = new Random();
for (int i = 0; i < 100; i++) {
Thread.sleep(0);
new Thread(new Runnable() {
public void run() {
try {
c.count();
Thread.sleep(rand.nextInt() % 2 + 2);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(c.getCount());
}
}).start();
}
}
}
public static void main(String[] args) throws InterruptedException {
final Counter_ThreadSafe c = new Counter_ThreadSafe();
final Random rand = new Random();
for (int i = 0; i < 100; i++) {
Thread.sleep(0);
new Thread(new Runnable() {
public void run() {
try {
c.count();
Thread.sleep(rand.nextInt() % 2 + 2);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println(c.getCount());
}
}).start();
}
}
}