java多线程简单练习

 使用ReentrantLock或者AtomicInteger实现此处的计数安全;

public class ThreadTest {
    public ReentrantLock lock = new ReentrantLock();
    // public AtomicInteger a = new AtomicInteger(0);
    public static int a = 0;

    public void test() {
        try {
            lock.lock();
            a++;
        } finally {
            lock.unlock();
        }
    }

    public static void test2() throws InterruptedException {
        ThreadTest threadTest = new ThreadTest();

        Vector<Thread> queue = new Vector<>();
        for (int i = 0; i < 400; i++) {
            Thread thread = new Thread(() -> {
                for (int j = 0; j < 5; j++) {
                    threadTest.test();
                    System.out.println(Thread.currentThread().getName() + ":" + threadTest.a);
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            queue.add(thread);
            thread.start();
        }
        for (Thread t : queue) {
            t.join();
        }
        System.out.println("size:"+queue.size());
    }

    public static void main(String[] args) throws InterruptedException {
        long start = System.currentTimeMillis();
        test2();
        System.out.println("耗时:" + (System.currentTimeMillis() - start));
    }
}

 使用线程池控制多线程安全:

   线程池使用优点:

     可以复用,减少线程创建销毁开销;

     超过核心线程数任务会安排在队列里,不会因阻塞造成线程上下文频繁切换; 

     线程池集中管理;

public class ThreadLocalTest {
    public static int a = 0;
    //定义一个定长线程池
    public static ExecutorService executorService = Executors.newScheduledThreadPool(10);

    public static void main(String[] args) {
        for (int i = 0; i < 200; i++) {
            executorService.execute(() -> {
                System.out.println(++a);
            });
        }
        executorService.shutdown();
        try {
            executorService.awaitTermination(3, TimeUnit.MICROSECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(a);
        }
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值