原子类测试

package t1;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

public class TestThread23 {
private static AtomicLong nextId = new AtomicLong(1);// 原子
private static volatile Long addLong = 1L;// 非可见 加上volatile修饰可满足可见性有序性、但还是非原子操作

static long getNext() {
return nextId.getAndIncrement();
}

static long getAddLong() {
return addLong++;
}

Runnable r = () -> {
System.out.println(Thread.currentThread().getName() + ":" + getNext());
};
Runnable r1 = () -> {
System.out.println(Thread.currentThread().getName() + ":" + getAddLong());
};
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);

Thread t3 = new Thread(r1);
Thread t4 = new Thread(r1);

public static void main(String[] args) throws InterruptedException {
TestThread23 t = new TestThread23();
t.t1.start();
t.t2.start();
TimeUnit.SECONDS.sleep(1);
System.out.println();

t.t3.start();
t.t4.start();
}

}

测试结果:

扫描二维码关注公众号,回复: 10373461 查看本文章

或者

猜你喜欢

转载自www.cnblogs.com/dengw125792/p/12611878.html