//$Id$
import java.util.logging.Level;
import java.util.logging.Logger;
public class ThreadSafe {
public static final Logger LOGGER = Logger.getLogger(ThreadSafe.class.getName());
public static int random(int num){
LOGGER.log(Level.INFO,"Entered Num : {0}",num);
try {
Thread.sleep(5);
} catch (InterruptedException e) {
LOGGER.log(Level.INFO,"Interrupted Exception");
}
return num + 2;
}
public static void main(String[] args){
for(int threads=1;threads<100;threads++){
final int number = threads;
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
int val = ThreadSafe.random(number);
System.out.println("Excepted Value = " + (number+2) + " Returned Value = " + val);
}
},"Thread : "+threads);
thread.start();
}
}
}
输出:
30 Jan, 2013 11:41:26 PM com.zoho.learn.test.ThreadSafe random
INFO: Entered Num : 2
30 Jan, 2013 11:41:26 PM com.zoho.learn.test.ThreadSafe random
INFO: Entered Num : 45
30 Jan, 2013 11:41:26 PM com.zoho.learn.test.ThreadSafe random
INFO: Entered Num : 44
30 Jan, 2013 11:41:26 PM com.zoho.learn.test.ThreadSafe random
INFO: Entered Num : 43
30 Jan, 2013 11:41:26 PM com.zoho.learn.test.ThreadSafe random
INFO: Entered Num : 42
30 Jan, 2013 11:41:26 PM com.zoho.learn.test.ThreadSafe random
INFO: Entered Num : 38
Excepted Value = 47 Returned Value = 47
30 Jan, 2013 11:41:26 PM com.zoho.learn.test.ThreadSafe random
INFO: Entered Num : 41
Excepted Value = 44 Returned Value = 44
Excepted Value = 46 Returned Value = 46
我排除了同时访问同一方法的多线程。如果我们同时访问一个静态方法会发生什么?
什么时候出现竞态条件?
什么是共享状态?
如果我错了,请纠正我。