首页 > 其他分享 >多线程入门Demo

多线程入门Demo

时间:2024-08-22 23:52:54浏览次数:11  
标签:入门 int Demo containerNum System cpuNum future taskTime 多线程

package run;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TheadDemo01 {

	public static void main(String[] args) {
		int containerNum = 800;
		int taskTime = 40;
		singleThreadRun(containerNum, taskTime);
		manyThreadRun(containerNum, taskTime);
		manyThreadRunByCompletionService(containerNum, taskTime);
		manyThreadRunByCompletionServiceTest(containerNum, taskTime);
		manyThreadRunByCompletionServiceTest2(containerNum, taskTime);
	}

	/**
	 * 单线程运行速度
	 * 
	 * @param containerNum
	 * @param taskTime
	 */
	public static void singleThreadRun(int containerNum, int taskTime) {
		int result = 0;
		long start = System.currentTimeMillis();
		for (int i = 0; i < containerNum; i++) {
			try {
				// 模拟运行任务
				Thread.sleep(taskTime);
				result += 1;
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		long end = System.currentTimeMillis();
		System.out.println("Single Thread RunTime : " + (end - start));
		System.out.println("Single Thread Result : " + result);
	}

	/**
	 * 运行时阻塞多线程
	 * 
	 * @param containerNum
	 * @param taskTime
	 */
	public static void manyThreadRun(int containerNum, int taskTime) {
		int cpuNum = Runtime.getRuntime().availableProcessors();
		System.out.println(cpuNum);
		ThreadPoolExecutor excutor = new ThreadPoolExecutor(cpuNum, cpuNum, 60L, TimeUnit.SECONDS,
				new LinkedBlockingQueue<>(1000));

		int result = 0;
		long start = System.currentTimeMillis();
		List<Future<Integer>> futures = new ArrayList<>();
		for (int i = 0; i < containerNum; i++) {
			Future<Integer> future = excutor.submit(() -> {
				// 模拟运行任务
				Thread.sleep(taskTime);
				return 1;
			});
			futures.add(future);
		}
		for (int i = 0; i < containerNum; i++) {
			Future<Integer> future = futures.get(i);
			try {
				// futures.get()会阻塞线程
				Integer futureResult = future.get();
				result += futureResult;
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		}
		excutor.shutdown();
		long end = System.currentTimeMillis();
		System.out.println("Many Thread RunTime : " + (end - start));
		System.out.println("Many Thread Result : " + result);
	}

	/**
	 * 运行结果阻塞多线程
	 * 
	 * @param containerNum
	 * @param taskTime
	 */
	public static void manyThreadRunByCompletionService(int containerNum, int taskTime) {
		int cpuNum = Runtime.getRuntime().availableProcessors();
		System.out.println(cpuNum);
		ThreadPoolExecutor excutor = new ThreadPoolExecutor(cpuNum, cpuNum, 60L, TimeUnit.SECONDS,
				new LinkedBlockingQueue<>(1000));
		CompletionService<Integer> completionService = new ExecutorCompletionService<>(excutor);
		int result = 0;
		long start = System.currentTimeMillis();
		List<Future<Integer>> futures = new ArrayList<>();
		for (int i = 0; i < containerNum; i++) {
			Future<Integer> future = completionService.submit(() -> {
				// 模拟运行任务
				Thread.sleep(taskTime);
				return 1;
			});
			futures.add(future);
		}
		for (int i = 0; i < containerNum; i++) {
			try {
				Future<Integer> future = completionService.take();
				Integer futureResult = future.get();
				result += futureResult;
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		}
		long end = System.currentTimeMillis();
		excutor.shutdown();
		System.out.println("CompletionService Many Thread RunTime : " + (end - start));
		System.out.println("CompletionService Many Thread Result : " + result);
	}

	// 问:测试1和测试2的区别在哪?

	/**
	 * 测试1
	 * 
	 * @param containerNum
	 * @param taskTime
	 */
	public static void manyThreadRunByCompletionServiceTest(int containerNum, int taskTime) {
		int cpuNum = Runtime.getRuntime().availableProcessors();
		System.out.println(cpuNum);
		ThreadPoolExecutor excutor = new ThreadPoolExecutor(cpuNum, cpuNum, 60L, TimeUnit.SECONDS,
				new LinkedBlockingQueue<>(1000));
		CompletionService<Integer> completionService = new ExecutorCompletionService<>(excutor);
		int result = 0;
		long start = System.currentTimeMillis();

		for (int i = 0; i < containerNum; i++) {
			List<Future<Integer>> futures = new ArrayList<>();
			for (int j = 0; j < 1; j++) {
				Future<Integer> future = completionService.submit(() -> {
					// 模拟运行任务
					Thread.sleep(taskTime);
					return 1;
				});
				futures.add(future);
			}

			for (int j = 0; j < futures.size(); j++) {
				try {
					Future<Integer> future = completionService.take();
					Integer futureResult = future.get();
					result += futureResult;
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (ExecutionException e) {
					e.printStackTrace();
				}
			}
		}

		long end = System.currentTimeMillis();
		excutor.shutdown();
		System.out.println("CompletionService Test Many Thread RunTime : " + (end - start));
		System.out.println("CompletionService Test Many Thread Result : " + result);
	}

	/**
	 * 测试2
	 * 
	 * @param containerNum
	 * @param taskTime
	 */
	public static void manyThreadRunByCompletionServiceTest2(int containerNum, int taskTime) {
		int cpuNum = Runtime.getRuntime().availableProcessors();
		System.out.println(cpuNum);
		ThreadPoolExecutor excutor = new ThreadPoolExecutor(cpuNum, cpuNum, 60L, TimeUnit.SECONDS,
				new LinkedBlockingQueue<>(1000));
		CompletionService<Integer> completionService = new ExecutorCompletionService<>(excutor);
		int result = 0;
		long start = System.currentTimeMillis();

		List<Future<Integer>> futures = new ArrayList<>();
		for (int i = 0; i < containerNum; i++) {
			for (int j = 0; j < 1; j++) {
				Future<Integer> future = completionService.submit(() -> {
					// 模拟运行任务
					Thread.sleep(taskTime);
					return 1;
				});
				futures.add(future);
			}
		}
		for (int j = 0; j < futures.size(); j++) {
			try {
				Future<Integer> future = completionService.take();
				Integer futureResult = future.get();
				result += futureResult;
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		}

		long end = System.currentTimeMillis();
		excutor.shutdown();
		System.out.println("CompletionService Test2 Many Thread RunTime : " + (end - start));
		System.out.println("CompletionService Test2 Many Thread Result : " + result);
	}
}

标签:入门,int,Demo,containerNum,System,cpuNum,future,taskTime,多线程
From: https://blog.csdn.net/2401_86904339/article/details/141440617

相关文章

  • C++设计模式1:单例模式(懒汉模式和饿汉模式,以及多线程问题处理)
    饿汉单例模式        程序还没有主动获取实例对象,该对象就产生了,也就是程序刚开始运行,这个对象就已经初始化了。 classSingleton{public: ~Singleton() { std::cout<<"~Singleton()"<<std::endl; } staticSingleton*get_instance() { return&sin......
  • linux的入门安装
    Linux的入门安装学习什么是操作系统操作系统:人与计算机硬件交互的中介,发送指令给操作系统,操作系统进行翻译,告诉计算机硬件,到底想干啥 操作系统,operatingsystem 简称os是计算机中必不可少的基础系统软件,是应用程序运行以及用户操作必备的基础运行环境,是计算机系统的核心......
  • 机器学习/数据分析--通俗语言带你入门K-邻近算法(结合案例)
    ......
  • Matplotlib基础入门--数据分析三大件完结
    Python数据分析三大件基础入门已经跟新完毕其余两篇如下:Numpy:《Python数据科学手册》—Numpy学习笔记(万字)Pandas:机器学习/数据分析–Pandas常用50个基础操作欢迎收藏+点赞+关注,下一步将更新机器学习/数据分析相关案例前言Matplotlib是python的一个绘图库,提......
  • 【redis数据库】基础入门,五种类型增删改查
    目录1.redis的启动2.redis基本操作3.redis的数据类型4.字符串操作添加修改值获取值5.键相关操作查找键判断键是否存在查看键对应的值类型设置已有键的过期时间查看键过期时间6.哈希操作添加值添加多个值获取字段获取字段对应的值获取多个字段的值获取所有字......
  • 【PHP安全】demo3:最简单的php代码加密方法
    当我们说"PHP代码加密",我理解的是将PHP代码进行混淆或加密,以防止源代码被他人轻易阅读或修改。这种需求通常用于保护商业秘密或加强代码安全性。常见的工具是使用专业的编译器和加密工具。然而,请注意,完全保护代码是不可能的,因为最终服务器仍然需要能够执行解密后的代码。以......
  • [小白入门]一文掌握C/C++中数组和循环结合(堵车问题、红绿灯问题)
    1.堵车问题假如现在给定从出发地到目的地的道路条数和每条路上的车辆情况为:第一条路第二条路第三条路第四条路第五条路第六条路90705278108120且车辆数大于50为轻度拥堵;大于70为中度拥堵;大于90为重度拥堵。那么如何存储这些数据?---很显然要用数......
  • redis入门
    1介绍1.1简介        Redis(RemoteDictionaryServer)是一个使用ANSIC编写的支持网络、基于内存、分布式、可选持久性的键值对存储数据库。根据月度排行网站DB-Engines.com的数据,Redis是最流行的键值对存储数据库。                      ......
  • 6D位姿检测FoundationPose demo测试
    Papertitle:FoundationPose:Unified6DPoseEstimationandTrackingofNovelObjectsPaperlink:https://arxiv.org/abs/2312.08344Codelink:GitHub-NVlabs/FoundationPose:[CVPR2024Highlight]FoundationPose:Unified6DPoseEstimationandTrackingof......
  • Git入门教程
    一、Git相关概念Git是一种分布式版本控制系统,主要用于跟踪和管理代码的变更。它由LinusTorvalds创建,最初被设计用于Linux内核的开发,现已成为软件开发过程中广泛使用的版本控制工具。1.基本概念版本控制:Git能够跟踪代码的每一次修改,并允许用户回滚到任何一个历史版本,这对......