Android并发编程之白话文详解Future,FutureTask和Callable

从最简单的说起Thread和Runnable

说到并发编程,就一定是多个线程并发执行任务。那么并发编程的基础是什么呢?没错那就是Thread了。一个Thread可以执行一个Runnable类型的对象。那么Runnable是什么呢?其实Runnable是一个接口,他只定义了一个方法run(),这个run()方法里就是我们要执行的任务,并且是要被Thread调用的。因此,一个Runnable就可以理解为一个要被执行的任务,而Thread就是一个执行任务的工人!
接下来我们用一个例子来实践一下,我们有一个任务(Runnable),这个任务就是来计算1+2+3+…+10,然后我们叫来一个工人(Thread)来执行这个任务。

public class ThreadDemo {
   
    public static void main(String[] args) {
        Thread worker = new Thread(new CountRunnable());
        worker.start();
    }
    public static class CountRunnable implements Runnable{
   
        private int sum;
        @Override
        public void run() {
            for(int i=1 ; i<11 ; i++){
                sum = sum+i;
            }
            System.out.println("sum="+sum);
        }

    }
}

这里写图片描述
这里我们调用了Thread的start()方法,相当于通知我们的工人去干活,然后工人Thread去调用任务Runnable的run()方法去干活。
这里写图片描述

如果我们觉得一个工人不够用,那么我们可以多叫来几个工人,让他们一起来工作,这就是并发编程了!

public class ThreadDemo {
   
    public static void main(String[] args) throws Exception{
        List<Thread> threads = new ArrayList<Thread>();
        for(int i=1 ; i<101 ; i++){
            Thread thread = new Thread(new CountRunnable(),"Thread"+i);
            threads.add(thread);
            thread.start();
        }
        for(Thread t : threads){
            t.join();
        }
        System.out.println("所有线程执行完毕!");

    }
    public static class CountRunnable implements Runnable{
   
        private int sum;
        @Override
        public void run() {
            for(int i=1 ; i<11 ; i++){
                sum = sum+i;
            }
            System.out.println(Thread.currentThread().getName()+"执行完毕 sum="+sum);
        }

    }
}

这里写图片描述
我们看到,每个sum都等于55,不是听说多线程并发执行会带来线程不安全的问题吗?其实这里我们是给每个工人分配一个只属于自己的任务,每个工人干自己的活,所以并不会影响到其他的人

Thread thread = new Thread(new CountRunnable(),"Thread"+i);

那么什么情况下会出现线程并发的问题的?我们要做的就是把一个任务同时分配给100名工人,那么就会出现线程不安全的问题

public class ThreadDemo {
   
    public static void main(String[] args) throws Exception{
        List<Thread> threads = new ArrayList<Thread>();
        //注意这里,我们在外面new出一个任务来,让100个线程都来执行这个任务
        CountRunnable work = new CountRunnable();
        for(int i=1 ; i<101; i++){
            Thread thread = new Thread(work,"Thread"+i);
            threads.add(thread);
        }
        for(Thread t : threads){
            t.start();
        }
        for(Thread t : threads){
            t.join();
        }
        System.out.println("所有线程执行完毕");

    }
    public static class CountRunnable implements Runnable{
   
        private 
  • 16
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值