关于synchronized关键字
package concurrency2;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class AtomicityTest implements Runnable
{
private int i=0;
public synchronized int getValue(){
return i;
}
private synchronized void evenIncrement()
{
i++;i++;
}
@Override
public void run()
{
while(true)
{
evenIncrement();
}
}
public static void main(String[] args)
{
ExecutorService es=Executors.newCachedThreadPool();
AtomicityTest at=new AtomicityTest();
es.execute(at);
while(true)
{
int val=at.getValue();
if (val%2!=0)
{
System.out.println(val);
System.exit(0);
}
}
}
}
我觉得程序在执行到at.getValue去return i 的时候,另外一个2个i++的循环,有可能只执行了一个i++啊,这样不也是线程不安全么?
synchronized关键字在里面起的作用不只是同步方法是么?求高手赐教
------解决方案--------------------找了许久,终于找到了~~~
http://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html
The Java programming language provides two basic synchronization idioms: synchronized methods and synchronized statements. The more complex of the two, synchronized statements, are described in the next section. This section is about synchronized methods.
To make a method synchronized, simply add the synchronized keyword to its declaration:
public class SynchronizedCounter {
private int c = 0;
public synchronized void increment() {
c++;
}
public synchronized void decrement() {
c--;
}
public synchronized int value() {
return c;
}
}
If count is an instance of SynchronizedCounter, then making these methods synchronized has two effects:
First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.