One, test int is thread unsafe
In Java, in the case of high concurrency/multithreading, the self-subtraction of int is not thread-safe, and the use of Atomicinteger can be guaranteed.
Package com.yezi.learn.atomic;
Import Java.util.concurrent.atomic.AtomicInteger;
/** * Created by Yezi on 2014/5/10.
* * Public class Testatomicinteger {private int sharei=0;
Private Atomicinteger Atomicloop = new Atomicinteger (0);
private int loop = 0;
public static void Main (String []args) throws exception{Testatomicinteger t = new Testatomicinteger ();
T.testmethod ();
System.out.println (t);
The public void TestMethod () throws exception{thread Th1 = new Thread (new ThreadTest ());
Thread Th2 = new Thread (new ThreadTest ());
Th1.start ();
Th2.start ();
Th1.join ();
Th2.join ();
Public synchronized void Add () {sharei++; Class ThreadTest implements runnable{@Override public void Run () {//testatomicinteger (
);
Testint (); } public void Testint () {//test, Output random, for thread unsafe for (; loop<100000;loop++) {ADD (); } public void Testatomicinteger () {//output 1000000, thread safe for (; Atomicloop.getandadd (1) <100000;)
{Add ();
@Override public String toString () {return "+sharei;
}
}
Second, Atomicintegerfieldupdater can be processed on the fields of obj
Package com.yezi.learn.atomic;
Import Java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
/** * Created by Yezi on 2014/5/10.
* * Public class Testatomicobjectinteger {private Looper looper = new Looper ();
private int sharei=0; public static void Main (String ... args) throws exception{Testatomicobjectinteger t = new Testatomicobjectinteger (
);
T.testmethod ();
System.out.println (t);
public void Testnormal () {//thread unsafe for (; Looper.getloop () <100000;looper.setloop (Looper.getloop () +1)) {
Add (); } public void Testuseatomic () {atomicintegerfieldupdater<looper> Atomicintegerfieldupdater =//Use
Atomic to Atomicintegerfieldupdater.newupdater (Looper.class, "loop");
for (; Atomicintegerfieldupdater.getandadd (looper,1) <100000;) {Add ();
The public void TestMethod () throws exception{thread Th1 = new Thread (new ThreadTest ()); ThreAd Th2 = new Thread (new ThreadTest ());
Th1.start ();
Th2.start ();
Th1.join ();
Th2.join ();
Class ThreadTest implements runnable{@Override public void Run () {testuseatomic ();
Testnormal ();
} public synchronized void Add () {sharei++;
@Override public String toString () {return sharei+ ""; Class looper{public volatile int loop=0;
The field to be controlled for atomicintegerfieldupdater must be public volatile public int Getloop () {return loop;
public void Setloop (int loop) {This.loop = loop;
}
}