多线程实践项目

前言

前面几篇文章分别学习了多线程的基本知识和线程池使用,这篇则为项目实践和整理。

项目参考

选择了两个项目github地址,如果不方便下载可以下面留言评论私发。
1.马士兵老师的juc,讲述了多线程的基本知识线程讲解
2.基本的线程演示:主要是对前面几篇讲解的回顾。
在这里插入图片描述

代码展示

BlockingQueue(阻塞队列)

package com.unicss;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
public class MyBlockingQueue extends Thread {
public static BlockingQueue<String> queue = new LinkedBlockingQueue<String>(3);
private int index;
public MyBlockingQueue(int i) {
   this.index = i;
}
public void run() {
   try {
    queue.put(String.valueOf(this.index));
    System.out.println("{" + this.index + "} in queue!");
   } catch (Exception e) {
    e.printStackTrace();
   }
}
public static void main(String args[]) {
   ExecutorService service = Executors.newCachedThreadPool();
   for (int i = 0; i < 10; i++) {
    service.submit(new MyBlockingQueue(i));
   }
   Thread thread = new Thread() {
    public void run() {
     try {
      while (true) {
       Thread.sleep((int) (Math.random() * 1000));
       System.out.println("======="+MyBlockingQueue.queue.size());
       if(MyBlockingQueue.queue.isEmpty())
        break;
       String str = MyBlockingQueue.queue.take();
       System.out.println(str + " has take!");
      }
     } catch (Exception e) {
      e.printStackTrace();
     }
    }
   };
   service.submit(thread);
   service.shutdown();
}
}

CompletionService(并发工具类,获取接口放回)

package com.unicss;

import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyCompletionService implements Callable<String> {
private int id;

public MyCompletionService(int i){
   this.id=i;
}
public static void main(String[] args) throws Exception{
   ExecutorService service=Executors.newCachedThreadPool();
   CompletionService<String> completion=new ExecutorCompletionService<String>(service);
   for(int i=0;i<10;i++){
    completion.submit(new MyCompletionService(i));
   }
   for(int i=0;i<10;i++){
    System.out.println(completion.take().get());
   }
   service.shutdown();
}

@Override
public String call() throws Exception {
	   Integer time=(int)(Math.random()*1000);
	   try{
	    System.out.println(this.id+" start");
	    Thread.sleep(time);
	    System.out.println(this.id+" end");
	   }
	   catch(Exception e){
	    e.printStackTrace();
	   }
	   return this.id+":"+time;
	}
}

Executor

package com.unicss;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyExecutor extends Thread {
private int index;
public MyExecutor(int i){
    this.index=i;
}
public void run(){
    try{
     System.out.println("["+this.index+"] start....");
     Thread.sleep((int)(Math.random()*10000));
     System.out.println("["+this.index+"] end.");
    }
    catch(Exception e){
     e.printStackTrace();
    }
}
public static void main(String args[]){
    ExecutorService service=Executors.newFixedThreadPool(4);
    for(int i=0;i<10;i++){
     service.execute(new MyExecutor(i));
     //service.submit(new MyExecutor(i));
    }
    System.out.println("submit finish");
    service.shutdown();
}
}

ReentrantLock(可重入到互斥锁)

package com.unicss;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;
public class MyReentrantLock extends Thread{
TestReentrantLock lock;
private int id;
public MyReentrantLock(int i,TestReentrantLock test){
    this.id=i;
    this.lock=test;
}
public void run(){
    lock.print(id);
}
public static void main(String args[]){
    ExecutorService service=Executors.newCachedThreadPool();
    TestReentrantLock lock=new TestReentrantLock();
    for(int i=0;i<10;i++){
     service.submit(new MyReentrantLock(i,lock));
    }
    service.shutdown();
}
}
class TestReentrantLock{
private ReentrantLock lock=new ReentrantLock();
public void print(int str){
    try{
     lock.lock();
     System.out.println(str+"获得");
     Thread.sleep((int)(Math.random()*1000));
    }
    catch(Exception e){
     e.printStackTrace();
    }
    finally{
     System.out.println(str+"释放");
     lock.unlock();
    }
}
}

Semaphore(信号量)

package com.unicss;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class MySemaphore extends Thread {
Semaphore position;
private int id;
public MySemaphore(int i,Semaphore s){
    this.id=i;
    this.position=s;
}
public void run(){
    try{
     if(position.availablePermits()>0){
      System.out.println("顾客["+this.id+"]进入厕所,有空位");
     }
     else{
      System.out.println("顾客["+this.id+"]进入厕所,没空位,排队");
     }
     position.acquire();
     System.out.println("顾客["+this.id+"]获得坑位");
     Thread.sleep((int)(Math.random()*1000));
     System.out.println("顾客["+this.id+"]使用完毕");
     position.release();
    }
    catch(Exception e){
     e.printStackTrace();
    }
}
public static void main(String args[]){
    ExecutorService list=Executors.newCachedThreadPool();
    Semaphore position=new Semaphore(2);
    for(int i=0;i<10;i++){
     list.submit(new MySemaphore(i+1,position));
    }
    list.shutdown();
    position.acquireUninterruptibly(2);
    System.out.println("使用完毕,需要清扫了");
    position.release(2);
}
}

CountDownLatch(倒计数器)

package com.unicss;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestCountDownLatch {
public static void main(String[] args) throws InterruptedException {
   // 开始的倒数锁
   final CountDownLatch begin = new CountDownLatch(1);
   // 结束的倒数锁
   final CountDownLatch end = new CountDownLatch(10);
   // 十名选手
   final ExecutorService exec = Executors.newFixedThreadPool(10);
  
   for (int index = 0; index < 10; index++) {
    final int NO = index + 1;
    Runnable run = new Runnable() {
     public void run() {
      try {
       begin.await();//一直阻塞
       Thread.sleep((long) (Math.random() * 10000));
       System.out.println("No." + NO + " arrived");
      } catch (InterruptedException e) {
      } finally {
       end.countDown();
      }
     }
    };
    exec.submit(run);
   }
   System.out.println("Game Start");
   begin.countDown(); //让技术器变为0执行

   end.await();//等待阻塞,计数器变为0 执行
   System.out.println("Game Over");
   exec.shutdown();
}
}

CyclicBarrier(同步屏障)

package com.unicss;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestCyclicBarrier {
  // 徒步需要的时间: Shenzhen, Guangzhou, Shaoguan, Changsha, Wuhan
  private static int[] timeWalk = { 5, 8, 15, 15, 10 };
  // 自驾游
  private static int[] timeSelf = { 1, 3, 4, 4, 5 };
  // 旅游大巴
  private static int[] timeBus = { 2, 4, 6, 6, 7 };
  
  static String now() {
     SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
     return sdf.format(new Date()) + ": ";
  }
  static class Tour implements Runnable {
     private int[] times;
     private CyclicBarrier barrier;
     private String tourName;
     public Tour(CyclicBarrier barrier, String tourName, int[] times) {
       this.times = times;
       this.tourName = tourName;
       this.barrier = barrier;
     }
     public void run() {
       try {
         Thread.sleep(times[0] * 1000);
         System.out.println(now() + tourName + " Reached Shenzhen");
         barrier.await();
         Thread.sleep(times[1] * 1000);
         System.out.println(now() + tourName + " Reached Guangzhou");
         barrier.await();
         Thread.sleep(times[2] * 1000);
         System.out.println(now() + tourName + " Reached Shaoguan");
         barrier.await();
         Thread.sleep(times[3] * 1000);
         System.out.println(now() + tourName + " Reached Changsha");
         barrier.await();
         Thread.sleep(times[4] * 1000);
         System.out.println(now() + tourName + " Reached Wuhan");
         barrier.await();
       } catch (InterruptedException e) {
       } catch (BrokenBarrierException e) {
       }
     }
  }
  public static void main(String[] args) {
     // 三个旅行团。 屏障为三个,必须三个到达屏障才会打开
     CyclicBarrier barrier = new CyclicBarrier(3);
     ExecutorService exec = Executors.newFixedThreadPool(3);
     exec.submit(new Tour(barrier, "WalkTour", timeWalk));
     exec.submit(new Tour(barrier, "SelfTour", timeSelf));
//当我们把下面的这段代码注释后,会发现,程序阻塞了,无法继续运行下去。
     exec.submit(new Tour(barrier, "BusTour", timeBus));
    //  exec.submit(new Tour(barrier, "liu", timeBus)); 如果单独加一个会阻塞在屏障上,必须根据设置是三个
     exec.shutdown();
  }
} 

ScheduledThread(定时线程)

package com.unicss;

/**
 * 定时器
 */
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
public class TestScheduledThread {
public static void main(String[] args) {

   final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
   final Runnable beeper = new Runnable() {
	    int count = 0;
	    public void run() {
	     System.out.println(new Date() + " beep " + (++count));
	    }
};
   // 1秒钟后运行,并每隔2秒运行一次
   final ScheduledFuture beeperHandle = scheduler.scheduleAtFixedRate(beeper, 1, 2, SECONDS);
   // 2秒钟后运行,并每次在上次任务运行完后等待5秒后重新运行
   final ScheduledFuture beeperHandle2 = scheduler.scheduleWithFixedDelay(beeper, 2, 5, SECONDS);
   // 30秒后结束关闭任务,并且关闭Scheduler
   scheduler.schedule(new Runnable() {
    public void run() {
     beeperHandle.cancel(true);
     beeperHandle2.cancel(true);
     scheduler.shutdown();
    }
   }, 30, SECONDS);
}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/292051.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

几种读nii图像方法的轴序比较

读 .nii / .nii.gz 图像并转成 numpy 可用 medpy.io、nibabel、itk、SimpleITK 几种方法&#xff0c;然而几种方法读出来的轴序有出入&#xff0c;本篇比较此几种方法。 Datum 所用数据来自 verse&#xff0c;经 iTomxy/data/verse/preprocess.py 预处理&#xff0c;朝向和轴…

【VTK三维重建-体绘制】第五期 vtkLODProp3D

很高兴在雪易的CSDN遇见你 VTK技术爱好者 QQ&#xff1a;870202403 前言 本文分享VTK中体绘制中的vtkLODProp3D对象&#xff0c;希望对各位小伙伴有所帮助&#xff01; 感谢各位小伙伴的点赞关注&#xff0c;小易会继续努力分享&#xff0c;一起进步&#xff01; 你的点赞…

【数据挖掘】基于 LightGBM 的系统访问风险识别(附源码)

基于 LightGBM 的系统访问风险识别 文章目录 基于 LightGBM 的系统访问风险识别一、课题来源二、任务描述三、课题背景四、数据获取分析及说明&#xff08;1&#xff09;登录https://www.datafountain.cn并获取相关数据&#xff08;2&#xff09;数据集文件说明&#xff08;3&a…

好代码网同款wordpress主题,适合搭建资源分享类网站,自带五六百的精品资源数据

代码简介&#xff1a; 好代码资源网是个还不错的资源分享类网站&#xff0c;基于wordpress搭建的。它的主题看起来还是不错的。这里分享一下这个网站的主题包。说是主题包&#xff0c;其实就是整站打包的&#xff0c;集成了主题&#xff08;wordpress美化主题包几个插件&#…

从vue小白到高手,从一个内容管理网站开始实战开发第六天,登录功能后台功能设计--API项目中的登录实现(一)

从vue小白到高手,从一个内容管理网站开始实战开发第五天,登录功能后台功能设计--数据库与API项目-CSDN博客文章浏览阅读348次,点赞9次,收藏7次。本次文章主要讲了开发后台API项目给前台vue调用的话,需要使用的数据库并新建数据库和表、安装开发工具、如何创建API项目以及A…

05-微服务-RabbitMQ-概述

RabbitMQ 1.初识MQ 1.1.同步和异步通讯 微服务间通讯有同步和异步两种方式&#xff1a; 同步通讯&#xff1a;就像打电话&#xff0c;需要实时响应。 异步通讯&#xff1a;就像发邮件&#xff0c;不需要马上回复。 两种方式各有优劣&#xff0c;打电话可以立即得到响应&am…

深入解析美颜SDK:绿幕抠图功能的算法原理

当下&#xff0c;美颜SDK绿幕抠图功能成为许多应用中不可或缺的一环。本文将深入解析美颜SDK中绿幕抠图功能的算法原理&#xff0c;揭示其背后的技术奥秘。 一、什么是美颜SDK绿幕抠图&#xff1f; 美颜SDK的绿幕抠图功能是一种通过计算机视觉技术&#xff0c;将视频或图像中…

十六:爬虫-验证码与字体反爬

一&#xff1a;验证码 验证码&#xff08;CAPTCHA&#xff09;是一种计算机程序设计技术&#xff0c;用于确定用户是人类而不是机器。它通常表现为一种图像或声音&#xff0c;要求用户在输入框中输入正确的文本或数字来证明自己是人类。因为机器人和计算机程序无法像人类一样理…

《深入理解C++11:C++11新特性解析与应用》笔记八

第八章 融入实际应用 8.1 对齐支持 8.1.1 数据对齐 c可以通过sizeof查询数据的长度&#xff0c;但是没有对对齐方式有关的查询或者设定进行标准化。c11标准定义的alignof函数可以查看数据的对齐方式。 现在的计算机通常会支持许多向量指令&#xff0c;4组8字节的浮点数据&a…

C++ namespace 学习

源自&#xff1a;【C】-命名空间的概念及使用_命名空间的概念及作用-CSDN博客 摘抄&#xff1a;

ISP 基础知识积累

Amber&#xff1a;现有工作必要的技术补充&#xff0c;认识需要不断深入&#xff0c;这个文档后续还会增加内容进行完善。 镜头成像资料 ——干货满满&#xff0c;看懂了这四篇文章&#xff0c;下面的问题基本都能解答 看完思考 1、ISP 是什么&#xff0c;有什么作用&#xff…

加密算法和身份认证

前瞻概念 在了解加密和解密的过程前&#xff0c;我们先了解一些基础概念 明文&#xff1a;加密前的消息叫 “明文” &#xff08;plain text&#xff09;密文: 加密后的文本叫 “密文” (cipher text)密钥: 只有掌握特殊“钥匙”的人&#xff0c;才能对加密的文本进行解密,这里…

前端实战第一期:悬浮动画

悬浮动画 像这样的悬浮动画该怎么做&#xff0c;让我们按照以下步骤完成 步骤&#xff1a; 先把HTML内容做起来&#xff0c;用button属性创建一个按钮&#xff0c;按钮内写上悬浮效果 <button classbtn>悬浮动画</button>在style标签内设置样式,先设置盒子大小&…

显示所有中国城市需要多少个汉字?

显示所有中国城市需要多少个汉字呢&#xff1f; 需要3678个汉字&#xff0c;看看我怎么知道的。 第一步&#xff1a;先找到中国的所有城市的名称 去哪里找到中国的所有城市的名称呢&#xff1f; 进入中国天气网&#xff1a;http://www.weather.com.cn/ 使用 F12 打开浏览器的调…

使用results.csv文件数据绘制mAP对比图

yolov5每次train完成&#xff08;如果没有中途退出&#xff09;都会在run目录下生成expX目录&#xff08;X代表生成结果次数 第一次训练完成生成exp0 第二次生成exp1…以此类推&#xff09;。expX目录下会保存训练生成的weights以及result.txt文件&#xff0c;其中weights是训练…

【MFC】计算机图形学实验:熟悉开发环境及工具(代码)

实验内容&#xff1a; 【MFC】计算机图形学实验1&#xff1a;熟悉开发环境及工具_绘制多义线mfc-CSDN博客 画笔和字体只给出两处代码&#xff1a; //创建刷子&#xff0c;设置填充色为黑色 CBrush NewBrush; NewBrush.CreateSolidBrush(RGB(0, 0, 0)); pDC->SelectObjec…

excel公式名称管理器

1.问题 在日常使用excel的时候&#xff0c;发布一个表格文件&#xff0c;需要限制表格的某列或某行只能从我们提供的选项中选择&#xff0c;自己随便填写视为无效&#xff0c;如下图所示&#xff0c;上午的行程安排只能从"在岗"、"出差"、"病假"…

seo分享:慎重使用蜘蛛池

其实要提高搜索引擎蜘蛛的来访次数&#xff0c;唯一的方法还是要通过网站本身的内容更新。频繁更新有质量的内容&#xff0c;才能够提高蜘蛛的来访次数。如果本身内容更新不多&#xff0c;外部引流的蜘蛛过多&#xff0c;最终发现没什么内容索引&#xff0c;蜘蛛来访的次数也会…

x-cmd pkg | 比 du 更好用的查看磁盘空间工具:dust

目录 简介首次用户技术特点竞品和相关作品进一步探索 简介 Dust 是一个用于分析磁盘空间使用情况的命令行工具&#xff0c;旨在提供直观的磁盘分布信息&#xff0c;它的名字是由 “du” 和 Rust 编程语言组合而来。 Dust 的主要功能是提供实时的磁盘空间概览&#xff0c;并以…

华为HCIE-Datacom课程介绍

厦门微思网络HCIE-Datacom课程介绍 一、认证简介 HCIE-Datacom&#xff08;Huawei Certified ICT Expert-Datacom&#xff09;认证是华为认证体系中的顶级认证&#xff0c;HCIE-Datacom认证定位具备坚实的企业网络跨场景融合解决方案理论知识&#xff0c;能够使用华为数通产品…
最新文章