java多线程笔记–Atomic原子操作类
1Atomic原子操作多线程计数
**
* @Description:
* Atomic原子操作类,用法简单,线程安全的更新变量
* @Author:
* @Date: 2019/5/14 23:56
*/
public class TestAtomicCount {
private static AtomicInteger num = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException{
for(int k=0;k<100;k++){
CountDownLatch countDownLatch = new CountDownLatch(3);
num.set(0);
Thread t1 =new Thread(new CountRunnable(countDownLatch));
Thread t2 =new Thread(new CountRunnable(countDownLatch));
Thread t3 =new Thread(new CountRunnable(countDownLatch));
t1.start();
t2.start();
t3.start();
countDownLatch.await();
System.out.println("第"+(k+1)+"次计算结果,num=" + num.get());
}
}
public static class CountRunnable implements Runnable{
private CountDownLatch countDownLatch;
CountRunnable (CountDownLatch countDownLatch){
this.countDownLatch=countDownLatch;
}
@Override
public void run() {
for (int i=0;i<10000;i++){
num.incrementAndGet();
// System.out.println(Thread.currentThread().getName()+":"+num);
}
countDownLatch.countDown();
}
}
}
2.synchronized多线程计数
**
* @Description:
* synchronized 来解决多线程更新变量的问题
* @Author:
* @Date: 2019/5/14 23:49
*/
public class TestThreadCount {
private static int num =0;
public static void main(String[] args)throws InterruptedException {
for(int k=0;k<100;k++){
CountDownLatch countDownLatch = new CountDownLatch(3);
num=0;
Thread t1 =new Thread(new CountRunnable(countDownLatch));
Thread t2 =new Thread(new CountRunnable(countDownLatch));
Thread t3 =new Thread(new CountRunnable(countDownLatch));
t1.start();
t2.start();
t3.start();
countDownLatch.await();
System.out.println("第"+(k+1)+"次计算结果,num=" + num);
}
}
public static class CountRunnable implements Runnable{
private CountDownLatch countDownLatch;
CountRunnable (CountDownLatch countDownLatch){
this.countDownLatch=countDownLatch;
}
@Override
public void run() {
//synchronized(this)代表锁住同一对象。
//synchronized(CountRunnable.class)代表锁住整个CountRunnable类的对象。
synchronized (CountRunnable.class){
for (int i=0;i<10000;i++){
num=num+1;
// System.out.println(Thread.currentThread().getName()+":"+num);
}
}
countDownLatch.countDown();
}
}
}