Java学习之Thread之Join、【Monitor】与【wait】与【notify】与【sleep】_加【Callable】【Executor】【ExecutorService】【Future】

本文主要是介绍Java学习之Thread之Join、【Monitor】与【wait】与【notify】与【sleep】_加【Callable】【Executor】【ExecutorService】【Future】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

■示例代码

代码(Join)

结果

■基础

【相同点】

【不同的】

■代码示例1(生产者与消费者)

0.ProductTest.java

1.Clerk.java

2.Consumer.java

3.Producer.java

■其他:代码示例2:(sleep,join)

■其他:线程的名字

■Callable、ExecutorService、Future

继承关系

示例代码

Callable和Future,一个产生结果,一个拿到结果。

FutureTask


■示例代码

代码(Join)

package com.sxz.study.thread;public class ThreadJoinStudy {public static void main(String[] args) throws InterruptedException {System.out.println("Main thread Start...");Thread threadB = new Thread(() -> {System.out.println("Thread B Start...");for (int i = 0; i < 5; i++) {System.out.println("Thread B Execute...");}System.out.println("Thread B End...");});threadB.start();// Thread B 加入 Main thread 流程// ★ 实现了Runnable接口的类,没法使用jion方法threadB.join(); System.out.println("Main thread End...");}}

结果

Main thread Start...
Thread B Start...
Thread B Execute...
Thread B Execute...
Thread B Execute...
Thread B Execute...
Thread B Execute...
Thread B End...
Main thread End...

===

■基础

进程:Process

线程:Thread

【相同点】

都会让线程进入阻塞(Blocked)状态

【不同的】

1.每一个Object对象,都有一个锁,【wait】会释放锁,【sleep】不会释放锁。(即,不会释放同步监视器)

详细解释
1.Monitor是一种用来实现同步的工具 (锁:【同步监视器】)
2.与每个java对象相关联,即每个java对象都有一个Monitor与之对应
3.Monitor是实现Sychronized(内置锁)的基础

  2.【wait】与【notify】是Object的方法。【sleep】是Thread的方法。

 3.【wait】与【notify】只能用于 【synchronized】同步块中

    【sleep】在任何地方都可以使用。

    (只是,【sleep】会抛出【InterruptedException】异常)

   JVM启动【main方法】,相当于启动了一个【主线程】。主线程,也就是负责执行main方法中的代码。所以

                   main中,可以sleep

                   main中,【Thread.currentThread().getName()】 ,可以得到值「main」

4.【wait】释放锁,解除对当前操作对象的占用,

5.关于阻塞后的唤醒:【sleep】自动唤醒。被【wait】的,需要其他【synchronized】同步块中,使用【notify】或【notifyAll】方法来唤醒。

6.唤醒 与 锁的释放

调用notify()并不立即释放锁。它只是告诉某个正在等待的线程可以被唤醒,当同步快的所有代码执行完之后,锁才会被真正释放。

7.   用法(套路)
  一般的用法
【等待-通知机制】,套路如下:
  1、Thread1中判断某一条件不成立while(!【condition】),然后调用wait()方法。
  2、Thread2中建立该条件如【condition】=true,然后调用notify()。
       ※【condition】是同一对象中的变量。(即, Thread1,2同时操作同一对象)

■代码示例1(生产者与消费者)

0.ProductTest.java

package com.sxz.study.thread;public class ProductTest {public static void main(String[] args) {Clerk clerk = new Clerk(); // 生产者线程Thread producerThread = new Thread(new Producer(clerk)); // 消费者线程Thread consumerThread = new Thread(new Consumer(clerk)); producerThread.start(); consumerThread.start(); }
}

1.Clerk.java

package com.sxz.study.thread;public class Clerk {// -1 表示目前没有产品private int product = -1; // 这个方法由生产者调用public synchronized void setProduct(int product) { if(this.product != -1) { try { // 目前店员没有空间收产品,请稍候!wait(); } catch(InterruptedException e) { e.printStackTrace(); } } this.product = product; System.out.printf("生产者设定 (%d)%n", this.product); // 通知等待区中的一个消费者可以继续工作了notify(); } // 这个方法由消费者调用public synchronized int getProduct() { if(this.product == -1) { try { // 缺货了,请稍候!wait(); } catch(InterruptedException e) { e.printStackTrace(); } } int p = this.product; System.out.printf("消費者取走 (%d)%n", this.product); this.product = -1; // 取走产品,-1表示目前店员手上无产品// 通知等待区中的一个生产者可以继续工作了notify(); return p; } 
} 

2.Consumer.java

package com.sxz.study.thread;public class Consumer implements Runnable {private Clerk clerk; public Consumer(Clerk clerk) { this.clerk = clerk; } public void run() { System.out.println("消费者开始消耗整数......"); // 消耗10个整数for(int i = 1; i <= 10; i++) { try { // 等待随机时间Thread.sleep((int) (Math.random() * 3000)); } catch(InterruptedException e) { e.printStackTrace(); } // 从店员处取走整数clerk.getProduct(); } } }

3.Producer.java

package com.sxz.study.thread;public class Producer implements Runnable {private Clerk clerk; public Producer(Clerk clerk) { this.clerk = clerk; } public void run() { System.out.println("生产者开始生产整数......"); // 生产1到10的整数for(int product = 1; product <= 10; product++) { try { // 暂停随机时间Thread.sleep((int) Math.random() * 3000); } catch(InterruptedException e) { e.printStackTrace(); } // 将产品交给店员clerk.setProduct(product); }       } 
}

---

运行结果

消费者开始消耗整数......
生产者开始生产整数......
生产者设定 (1)
消費者取走 (1)
生产者设定 (2)
消費者取走 (2)
生产者设定 (3)
消費者取走 (3)
生产者设定 (4)
消費者取走 (4)
生产者设定 (5)
消費者取走 (5)
生产者设定 (6)
消費者取走 (6)
生产者设定 (7)
消費者取走 (7)
生产者设定 (8)
消費者取走 (8)
生产者设定 (9)
消費者取走 (9)
生产者设定 (10)
消費者取走 (10)

---

■其他:代码示例2:(sleep,join)

public class ThreadA {public static void main(String[] args) {System.out.println("Thread A执行");Thread threadB = new Thread(new Runnable() { public void run() { try { System.out.println("Thread B开始.."); for(int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println("Thread B 执行.."); }System.out.println("Thread B  即将结束.."); } catch(InterruptedException e) { e.printStackTrace(); } } });threadB.start();try {// Thread B 加入 Thread AthreadB.join();} catch(InterruptedException e) { e.printStackTrace(); } System.out.println("Thread A 执行");}
}

---

■其他:线程的名字

// 每个线程,都有自己的名字
// JVM开启了主线程,来运行方法main,主线程也是线程,名字就是“main”    // 代码第6、7行
// 其他新建的线程也有名字,默认“Thread-0”,“Thread-1”...

package com.sxz.study.thread;public class ProductTest {public static void main(String[] args) throws InterruptedException {Clerk clerk = new Clerk(); Thread t =Thread.currentThread();System.out.println("Current Thread: " + t.getName());// 生产者线程Thread producerThread = new Thread(new Producer(clerk)); // 消费者线程Thread consumerThread = new Thread(new Consumer(clerk)); producerThread.start(); System.out.println(producerThread.getName());System.out.println(consumerThread.getName());consumerThread.start(); Thread.sleep(3000);System.out.println("Current Thread: " + t.getName());}
}

---

Current Thread: main
Thread-0
Thread-1
生产者开始生产整数......
消费者开始消耗整数......
生产者设定 (1)
消費者取走 (1)
生产者设定 (2)
消費者取走 (2)
生产者设定 (3)
Current Thread: main
消費者取走 (3)
生产者设定 (4)
消費者取走 (4)
生产者设定 (5)
消費者取走 (5)
生产者设定 (6)
消費者取走 (6)
生产者设定 (7)
消費者取走 (7)
生产者设定 (8)
消費者取走 (8)
生产者设定 (9)
消費者取走 (9)
生产者设定 (10)
消費者取走 (10)

---

■Callable、ExecutorService、Future

继承关系

示例代码

concurrent  英[kənˈkʌrənt]  adj.同时发生的; 并存的;  // java.util.concurrent.Callable // 线程与并行API

import java.util.concurrent.Callable;public class CallableDemo implements Callable<Integer> {private int sum;@Overridepublic Integer call() throws Exception {System.out.println("Callable子线程开始计算啦!");Thread.sleep(2000);for(int i=0 ;i<5000;i++){sum=sum+i;}System.out.println("Callable子线程计算结束!");return sum;}
}

Callable和Future,一个产生结果,一个拿到结果。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;public class CallableTest {public static void main(String[] args) {//创建线程池ExecutorService es = Executors.newSingleThreadExecutor();//创建Callable对象任务CallableDemo calTask=new CallableDemo();//提交任务并获取执行结果Future<Integer> future =es.submit(calTask);//关闭线程池es.shutdown();try {Thread.sleep(2000);System.out.println("主线程在执行其他任务");if(future.get()!=null){//输出获取到的结果System.out.println("future.get()-->"+future.get());}else{//输出获取到的结果System.out.println("future.get()未获取到结果");}} catch (Exception e) {e.printStackTrace();}System.out.println("主线程在执行完成");}
}

运行

set path=C:\java\java8\bin;%path%chcp 936javac -encoding UTF-8 CallableDemo.java
javac -encoding UTF-8 CallableTest.java
java CallableTestpause;

运行结果

Callable子线程开始计算啦!
主线程在执行其他任务
Callable子线程计算结束!
future.get()-->12497500
主线程在执行完成

--

FutureTask

(FutureTask实现了RunnableFuture接口,而RunnableFuture继承了Runnable和Future)

工作中使用到的单词(软件开发)_sun0322-CSDN博客

ーーー

这篇关于Java学习之Thread之Join、【Monitor】与【wait】与【notify】与【sleep】_加【Callable】【Executor】【ExecutorService】【Future】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/772520

相关文章

分布式锁在Spring Boot应用中的实现过程

《分布式锁在SpringBoot应用中的实现过程》文章介绍在SpringBoot中通过自定义Lock注解、LockAspect切面和RedisLockUtils工具类实现分布式锁,确保多实例并发操作... 目录Lock注解LockASPect切面RedisLockUtils工具类总结在现代微服务架构中,分布

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的

Spring Boot集成/输出/日志级别控制/持久化开发实践

《SpringBoot集成/输出/日志级别控制/持久化开发实践》SpringBoot默认集成Logback,支持灵活日志级别配置(INFO/DEBUG等),输出包含时间戳、级别、类名等信息,并可通过... 目录一、日志概述1.1、Spring Boot日志简介1.2、日志框架与默认配置1.3、日志的核心作用

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick

Spring WebClient从入门到精通

《SpringWebClient从入门到精通》本文详解SpringWebClient非阻塞响应式特性及优势,涵盖核心API、实战应用与性能优化,对比RestTemplate,为微服务通信提供高效解决... 目录一、WebClient 概述1.1 为什么选择 WebClient?1.2 WebClient 与

Java.lang.InterruptedException被中止异常的原因及解决方案

《Java.lang.InterruptedException被中止异常的原因及解决方案》Java.lang.InterruptedException是线程被中断时抛出的异常,用于协作停止执行,常见于... 目录报错问题报错原因解决方法Java.lang.InterruptedException 是 Jav