java多线程的实现和比较

一、继承Thread方法

代码实现如下:
(最基本实现,并没有截图运行结果,但是都是测试通过的,大家可以自己运行)

public class TestThread {

public static void main(String[] args) {
    int i=1,j=2,k=3;
    newThread thread1=new newThread(i);
    newThread thread2=new newThread(j);
    newThread thread3=new newThread(k);
    thread1.start();
    thread2.start();
    thread3.start();
}`
}

class newThread extends Thread{
private int i=5;

private int mark;

//这里可以添加子线程中的函数
public newThread(int mark){
    this.mark=mark;
}

public void run() {
    //这里实现方法体
    while(i>0){
        System.out.println("第 "+mark+" 个线程的值为:"+i--);
    }
    super.run();
}

二、实现Runnable接口

代码实现:
(体现出处理同一个资源方法)

entpublic static void main(String[] args) {
    newRunnable thread=new newRunnable();
    new Thread(thread,"1号").start();
    new Thread(thread,"2号").start();
    new Thread(thread,"3号").start();
}
}

class newRunnable implements Runnable{
private int i=5;
public void run() {
    while(i>0){
        System.out.println(Thread.currentThread().getName()+"  "+i--);
    }
}
}

比较:

1.Runnable接口适合多个相同程序代码的线程去处理同一个资源,例如卖票。

2.可以避免java中的单继承限制

3.增加程序的健壮性,代码可以被多个线程共享。

三、继承Callable接口

代码如下:

public class Callable {

public static void main(String[] args) {
    newCallable thread1 = new newCallable();
    ExecutorService pool = Executors.newSingleThreadExecutor();

    Future future = pool.submit(thread1);
    try {
        Integer data = (Integer) future.get();
        int i = data.intValue();
        System.out.println("计算的结果为:" + i);
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
}
}

class newCallable implements
java.util.concurrent.Callable {

public Object call() throws Exception {
    int sum = 0;
    for (int i = 0; i <= 100; i++) {
        sum = sum + i;
    }
    Integer returnData = new Integer(sum);
    return returnData;
}

区别

Callable接口和Runable接口最大的区别在于返回值,Callable接口允许有返回值。其中newFixedThreadPool()方法允许创建线程池。

后记

关于java多线程的资料非常多,我也是刚刚学习,深入到源码的也不会,重在对比这几种实现多线程的方案,大家可以参考代码。

引用

这篇博客分析非常详细,可以参考

深入分析各种机制

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值