多线程的四种实现简单源码分析

本文详细介绍了在Java中创建和管理线程的三种主要方式:继承Thread类、实现Runnable接口以及使用Callable接口配合FutureTask。对比了这三种方式的设计模式优劣,并展示了如何利用线程池进行高效的线程管理。

继承Thread类

步骤1:实现run方法

public class myThread extends  Thread {
    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            System.out.println("run=" + Thread.currentThread().getName());
        }
    }
}

步骤2:启动线程

 thread.start();

实现Runnable接口

同样的。
第一步:实现run方法

public class myRunnable implements  Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            System.out.println("run=" + Thread.currentThread().getName());
        }
    }
}

第二步:将runnable对象构造成thread对象,再调用thread的start()方法

myRunnable runnable =new myRunnable();
        Thread thread = new Thread(runnable) ;
        thread.start();
 

本质上没有区别,因为thread继承了runnable接口。
将myRunnable对象传进去,相当于重写thread的run方法。
只是在设计模式上有优劣。
Runnable 接口源码

@FunctionalInterface
public interface Runnable {
   
    public abstract void run();
}

   

然后再看Thread类中的run方法。这个run方法如果重写,子类就调用子类的run方法,如果不重写,就调用target的run方法。

 @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

初始化中target的run方法,不就是runnable中的run方法吗?

 public Thread(Runnable target) {
        init(null, target, "Thread-" + nextThreadNum(), 0);
    }

实现Callable接口通过FutureTask包装器来实现的线程

 class  Tickets<Object> implements Callable<Object> {

 @Override
public  Object call() {
     System.out.println(Thread.currentThread().getName());
     return null;
    }
}
public class TicketsTest {

    @Test
    public void call() {
        Callable<Object> oneCallable = new Tickets<Object>();
        FutureTask<Object> oneTask = new FutureTask<Object>(oneCallable);

        Thread t =new Thread(oneTask);
        System.out.println(Thread.currentThread().getName());
        t.start();
    }
}

线程池

public class myRunnable implements  Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            System.out.println("run=" + Thread.currentThread().getName());
        }
    }
}
 @Test
    public void run1() {

        ExecutorService executorService = Executors.newFixedThreadPool(5);
        for(int i = 0; i<POOL_NUM; i++)
        {
            myRunnable thread = new myRunnable();

            //Thread.sleep(1000);
            executorService.execute(thread);
        }
        //关闭线程池
        executorService.shutdown();
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值