Skip to end of metadata
Go to start of metadata
Advantage: you set a dedicated name to your working thread to make the thread trouble shooting more transparent.
Example:
public class AtomIntTest {
private AtomicInteger atomicI = new AtomicInteger(0);
private int i = 0;
public static void main(String[] args) {
final AtomIntTest cas = new AtomIntTest();
final int TOTAL_THREAD_NUM = 1;
List<Thread> ts = new ArrayList<Thread>();
long start = System.currentTimeMillis();
for (int j = 0; j < TOTAL_THREAD_NUM; j++) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
Thread.currentThread().setName(AtomIntTest.class.getName() + Thread.currentThread().getId());
for (int i = 0; i < 1000; i++) {
cas.count(); // i++
cas.safeCount();
}
System.out.println("Thread name: " + Thread.currentThread().getName());
}
});
ts.add(t);
}
System.out.println("total thread number: " + ts.size());
for (Thread t : ts) { // start 600 threads
t.start();
}
// wait all threads execution until finished
for (Thread t : ts) {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("unsafe: " + cas.i);
System.out.println("safe: " + cas.atomicI.get());
// System.out.println(System.currentTimeMillis() - start);
}
/**
*
* use CAS to achieve thread-safe counter
*/
private void safeCount() {
for (;;) {
int i = atomicI.get();
boolean suc = atomicI.compareAndSet(i, ++i);
if (suc) {
break;
}
}
}
/**
*
* non thread-safe counter
*/
synchronized private void count() {
i++;
}
}
Before setName is called, thread name is automatically generated by JVM is not so human readable:
After setName:


  • No labels