多线程——线程安全(synchronized,AtomicInteger),多线程求和(Thread与future)

相关链接 java 多线程求和的几种实现方式

多个线程操作同一个变量会存在线程安全问题
5个线程对一个数进行操作加一,使用CountDownLatch计数器来等待每一个线程执行结束

方法一(使用synchronized加锁)

package com.example.shiyan.thread;

import java.util.concurrent.CountDownLatch;

public class AtomicIntegerTest2 {

    //一个变量a
    private static volatile int a = 0;
    public static void main(String[] args) {
        CountDownLatch count = new CountDownLatch(5);
        Thread[] threads = new Thread[5];

        //定义5个线程,每个线程加10
        for (int i = 0; i < 5; i++) {
            threads[i] = new Thread(() -> {

                try {
                    synchronized (AtomicIntegerTest2.class){
                        for (int j = 0; j < 10; j++) {
                            System.out.println(a++);
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    count.countDown();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            });
            threads[i].start();

        }

        try {
            count.await();
            System.out.println("===>"+a);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        try {
//            Thread.sleep(10000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

    }


}

方法二(使用AtomicInteger原子类)

  • Atomic类用CAS实现,CAS使用unsafe类实现,unsafe会调用相应的native方法
package com.example.shiyan.thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerTest {
    //一个变量a
    static AtomicInteger a = new AtomicInteger();
    public static void main(String[] args) {
        CountDownLatch count = new CountDownLatch(5);
        Thread[] threads = new Thread[5];
        //定义5个线程,每个线程加10
        for (int i = 0; i < 5; i++) {
            threads[i] = new Thread(() -> {
                try {
                        for (int j = 0; j < 10; j++) {
                            System.out.println(a.incrementAndGet());
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    count.countDown();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            threads[i].start();

        }
//        try {
//            Thread.sleep(10000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        try {
            count.await();
            System.out.println("===>"+a);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }


}

多线程求和

用多线程计算1到100的和

package com.example.shiyan.thread;

import java.util.concurrent.Callable;

public class AddOperationPool implements Callable<Integer> {

    private int start;
    private int end;
    private int sum;

    public AddOperationPool(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    public Integer call() throws Exception {
        for (int i = start; i <= end; i++) {
            sum = sum + i;
        }
        return sum;
    }

}
package com.example.shiyan.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class AddOperationPoolTest {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        int sum = 0;
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
        List<Future<Integer>> futures = new ArrayList<>();

        for (int i = 1; i <= 10; i++) {
            AddOperationPool addOperationPool = new AddOperationPool((i - 1) * 10 + 1, 10 * i);
            Future<Integer> submit = fixedThreadPool.submit(addOperationPool);
            futures.add(submit);
        }
        if (null != futures && !futures.isEmpty()) {
            for (Future<?> future : futures) {
                Integer result = (Integer) future.get();
                sum = sum + result;
            }
        }
        System.out.println(sum);
        fixedThreadPool.shutdown();
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值