这篇文章给大家分享的是有关java中多线程与线程池怎么用的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
继承Thread去执行任务,确实可以开启一个线程去执行任务,如果经常的去开启一些线程,也会导致系统资源的浪费。
public static class Mythread extends Thread{
@Override
public void run() {
System.out.println("当前线程"+Thread.currentThread().getId());
int i = 10/2;
System.out.println("运行结果"+i);
}
}
//调用线程。
public static void main(String[] args) throws ExecutionException, InterruptedException {
/**thread执行方式*/
Mythread mythread = new Mythread();
mythread.start();//启动线程
System.out.println("main--end");
}
public static class MyRunable implements Runnable {
@Override
public void run() {
System.out.println("当前线程"+Thread.currentThread().getId());
int i = 10/2;
System.out.println("运行结果"+i);
}
}
调用。
/**
* runable的启动方式
*/
MyRunable runable = new MyRunable();
new Thread(runable).start();
System.out.println("main--end");
/**
* Callable可以允许有返回值
*/
public static class Callale01 implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("当前线程"+Thread.currentThread().getId());
int i = 10/2;
System.out.println("运行结果"+i);
return i;
}
}
调用。这里需要用callable构建futureTask
/**
* callale的启动方式
*/
FutureTask<Integer> futureTask =new FutureTask<>(new Callale01());
//取返回结果。
Integer i = futureTask.get();
new Thread(futureTask).start();
System.out.println("返回结果是:"+i);
线程池才是我们java开发中,经常用到一种开启多线程的方式,线程池,自己去管理线程。可以节省系统资源。通常我们会将下面的一些配置写在一些配置类中
/**
* 七大参数
* corePoolSize: 1.核心线程数[一直存在]: 线程池创建好了以后。就准备就绪的线程数量。
* maxinumPoolSize: 2 最大线程数量
* keepaliveTime: 存活时间。空闲线程的最大的等待时间。
* unit 等待时间的单位
* blockingQueue 阻塞队列。如果任务很多就会放在队列里面,只要有线程空闲了,就会去队列里面去取。
* threadFactory :线程的工厂。
* RejectExecutionHandler :如果队列满了。按照我们指定的策略。拒绝执行任务。
*
*/
ThreadPoolExecutor executor = new ThreadPoolExecutor(5,100,10,TimeUnit.SECONDS,
new LinkedBlockingQueue<>(100),
Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
1 newCachedThreadPool()
创建一个可缓存的线程池,如果线程池长度超过了处理的需要,可灵活的回收空闲线程。若无可回收。则创建新线程。
Executors.newCachedThreadPool();
2.newFixedThreadPool(6)
创建一个固定大小的线程池。
3 newScheduledThreadPool()
定时任务的线程池。
4.newSingleThreadExecutor()
Executors.newSingleThreadExecutor();
感谢各位的阅读!关于“java中多线程与线程池怎么用”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。