Java进阶学习2-多线程实现的3种方式

1.直接继承Thread类,重写run方法,例子

package snippet;
public class test {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            new MyThread().start();
        }
    }
}
class MyThread extends Thread {
    @Override
    public void run() {
        for (int i = 1; i < 100; i++) {
            System.out.println(getName() + "--->" + i);
        }
    }
}

2.使用Runable接口,作为Thread 参数传入(与上面没有什么不同,只是为了减少设计的藕性),例子

package snippet;
public class test {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            new Thread(new MyRunnable()).start();
        }
    }
}
class MyRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 1; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + "--->" + i);
        }
    }
}

注意,当实现Runable接口并且覆写Thread的run方法时,只会调用Thread的run方法.

3.使用Runable接口,使用Runable接口比较复杂,需要使用到线程池,但是它可以带返回值.先不管,看一下例子的代码

package snippet;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class MyCallable implements Callable<Integer> {
    
    private int    num1;
    private int    num2;
                
    public MyCallable(int num1, int num2) {
        try {
            this.num1 = num1;
            this.num2 = num2;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public Integer call() throws Exception {
        return num1 + num2;
    }
    
}
public class test {
    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newCachedThreadPool();
        /**
         * 创建一个线程池
         */
        List<Future<Integer>> results = new ArrayList<>();
        /**
         * Future<T>是泛型接口,其中泛型为返回数据类型
         */
        
        for (int i = 0; i < 5; i++) {
            Future<Integer> result = pool.submit(new MyCallable(i, i + 1));
            results.add(result);
        }
        
        for (int i = 0; i < results.size(); i++) {
            System.out.println(results.get(i).get());
        }
        /**
         * 使用get去获取call方法返回的值,可设置超时. 因为有时候若等待时间太长,则造成体验不好
         */
    }
}


转载于:https://my.oschina.net/august1996/blog/661122

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值