当前位置: 首页 > news >正文

Java / Android 多线程和 synchroized 锁

s

AsyncTask 在Android R中标注了废弃 

synchronized 同步

Thread:

thread.start()

 public synchronized void start() {/*** This method is not invoked for the main method thread or "system"* group threads created/set up by the VM. Any new functionality added* to this method in the future may have to also be added to the VM.** A zero status value corresponds to state "NEW".*/if (threadStatus != 0)throw new IllegalThreadStateException();/* Notify the group that this thread is about to be started* so that it can be added to the group's list of threads* and the group's unstarted count can be decremented. */group.add(this);boolean started = false;try {start0();started = true;} finally {try {if (!started) {group.threadStartFailed(this);}} catch (Throwable ignore) {/* do nothing. If start0 threw a Throwable thenit will be passed up the call stack */}}}private native void start0();

start0 是个native方法

进程和线程 进程> 线程

进程= 操作系统独立区域 ,可以有多条线程

进程和线程可以进行并行工作,线程依赖进程

Runable: 接口 重写run

new Thread(runnable)

thread.start(runnable)  runnable在Thread内部标为target

相比于thread,runnable可以重用 : Thread1(runnable),Thread2(runnable)

ThreadFactory: Thread 工厂方法
  private static void threadFactory() {AtomicInteger count = new AtomicInteger(0);ThreadFactory factory = new ThreadFactory() {@Overridepublic Thread newThread(Runnable r) {return new Thread(r,"Thread-"+count.incrementAndGet());}};Runnable runnable = new Runnable() {@Overridepublic void run() {System.out.println(Thread.currentThread().getName());}};Thread thread = factory.newThread(runnable);thread.start();Thread thread1 = factory.newThread(runnable);thread1.start();}

Executor: 接口

   private static void executor() {Runnable runnable = new Runnable() {@Overridepublic void run() {System.out.println("runnable run");}};Executor executor = Executors.newCachedThreadPool();executor.execute(runnable);executor.execute(runnable);executor.execute(runnable);}
public interface Executor {/*** Executes the given command at some time in the future.  The command* may execute in a new thread, in a pooled thread, or in the calling* thread, at the discretion of the {@code Executor} implementation.** @param command the runnable task* @throws RejectedExecutionException if this task cannot be* accepted for execution* @throws NullPointerException if command is null*/void execute(Runnable command);
}

newCachedThreadPool 返回 ExecutorService

void shutdown(); //关闭任务
List<Runnable> shutdownNow();//立即关闭 但是会调用intrat 用这个是安全的

  public static ExecutorService newCachedThreadPool() {return new ThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,new SynchronousQueue<Runnable>());}

内部创建线程池,和连接池一样. 包含了线程的创建 销毁等操作 (0 //默认大小,当超过最大值Integer.MAX_VALUE,就会销毁到默认大小)

60L, TimeUnit.SECONDS,线程等待回收时间
 new SynchronousQueue<Runnable>() 创建队列

Executor executor1 = Executors.newSingleThreadExecutor();创建1个线程
   public static ExecutorService newSingleThreadExecutor() {return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>()));}
  public static ExecutorService newFixedThreadPool(int nThreads) {return new ThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());}

newFixedThreadPool 创建固定数量的线程,不推荐,如果用得少或者不用也会是这么多,而且不可扩展更多,用来处理多个集中任务

newScheduledThreadPool:可以添加延迟
  public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {return new ScheduledThreadPoolExecutor(corePoolSize);}
Callable:有返回值的Runnable ,方法 call : Type

  private static void callable() {Callable<String> callable = new Callable<String>() {@Overridepublic String call() throws Exception {return "666";}};ExecutorService executorService = Executors.newCachedThreadPool();Future<String> future = executorService.submit(callable); //后台任务Future 否则就会阻塞主线程  execure则会阻塞进行等待try {String result = future.get(); //阻塞进行取值,System.out.println(result);} catch (ExecutionException | InterruptedException e) {throw new RuntimeException(e);}}if (future.isDone()){//如果完成任务}

流程图

线程同步:

public class SynchronizedDemo1 implements TestDemo{private boolean running =true;private void stop(){running = false;}@Overridepublic void runTest() {new Thread(new Runnable() {@Overridepublic void run() {int round = 1;while (running){}}}).start();try {Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}stop();}
}

看出会等待1秒然后跳出循环,但是实际上会一直执行 

每个线程都有一块独立的区域,会把变量copy,然后改变值,然后再传回去

但是如果是多线程,copy同一个值,进行修改,数据会乱

可以使用 volatile ,改变其内存可见性,同步

多线程中如若用

x++; 则会进行两步 1 int temp = x+1, 2  x = temp 不是原子操作

需要使用 synchronized 有线程调用则其他线程等待

private synchronized void count(){x++; 
}

AtomicInteger = int 的包装 增加原子性和同步性

AtomicInteger count = new AtomicInteger(0); //int
   AtomicInteger count = new AtomicInteger(0); //intThreadFactory factory = new ThreadFactory() {@Overridepublic Thread newThread(Runnable r) {return new Thread(r,"Thread-"+count.incrementAndGet()); //++count// count.getAndIncrement() //count++}};
AtomicBoolean
    private AtomicBoolean running = new AtomicBoolean(true);running.set(false);running.get()

除此之外还有

//同一个类如果有多个synchronized 一般就是有一个监视器 monitor 进行控制,只能由一个线程调用

可以再方法内部加上

synchronized (this){用当前监视器}

synchronized在方法上会同步锁多个方法,仅供当前线程调用

public class SynchronizedDemo3 implements TestDemo{private int x= 0;private int y = 0;private String name;private Object monitor1 = new Object();private Object monitor2 = new Object();private synchronized void count(int newValue){synchronized (monitor1){x = newValue;y = newValue;}}private void  minus(int delta){synchronized (monitor1){x -= delta;y -= delta;}}//synchronized 锁住当前方法private synchronized void setName(String name){synchronized (monitor2){this.name = name;}}@Overridepublic void runTest() {}
}

synchronized 在方法上等同于在内部的 synchronized (this)

synchronized 作用 = 同步性,互斥

死锁:多线程中,当前线程持有的锁,但拿不到需要进行执行代码中的锁,会一直等待

乐观锁 写入时先读取, 悲观锁 -读之前加锁,写入前加锁, 主要用于数据库

static 修饰的方法 用synchronized在方法上 等同于 在方法内部( synchronized (name.class))

用当前类当做锁

单例模式双重检查锁 写法1

ReentrantLock 可重入锁 需要手动加解锁,同时也要注意是否能够正常解锁

可以使用读写锁

 private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();Lock readLock = lock.readLock();Lock writeLock = lock.writeLock();

线程安全本质是多个线程访问共同资源,在写入时,其他线程干预了,导致数据错误

锁机制是:对资源进行访问的一种限制

相关文章:

Java / Android 多线程和 synchroized 锁

s AsyncTask 在Android R中标注了废弃 synchronized 同步 Thread: thread.start() public synchronized void start() {/*** This method is not invoked for the main method thread or "system"* group threads created/set up by the VM. Any new functionali…...

基于51单片机的万年历-脉搏计仿真及源程序

一、系统方案 1、本设计采用51单片机作为主控器。 2、DS1302采集年月日时分秒送到液晶1602显示。 3、按键年月日时分秒&#xff0c;心率报警上下限。 4、红外对接管传感器采集心率送到液晶1602显示。 5、心率低于下限或高于上限&#xff0c;蜂鸣器报警。 二、硬件设计 原理图如…...

【ARFoundation学习笔记】点云与参考点

写在前面的话 本系列笔记旨在记录作者在学习Unity中的AR开发过程中需要记录的问题和知识点。主要目的是为了加深记忆。其中难免出现纰漏&#xff0c;更多详细内容请阅读原文以及官方文档。 汪老师博客 文章目录 点云新建点云 参考点参考点的工作原理何时使用参考点使用参考点…...

uni-app:js实现数组中的相关处理-数组复制

一、slice方法-浅拷贝 使用分析 创建一个原数组的浅拷贝&#xff0c;对新数组的修改不会影响到原数组slice() 方法创建了一个原数组的浅拷贝&#xff0c;这意味着新数组和原数组中的对象引用是相同的。因此&#xff0c;当你修改新数组中的对象时&#xff0c;原数组中相应位置的…...

8 STM32标准库函数 之 实时时钟(RTC)所有函数的介绍及使用

8 STM32标准库函数 之 实时时钟(RTC)所有函数的介绍及使用 1. 图片有格式2 文字无格式二、RTC库函数固件库函数预览2.1 函数RTC_ITConfig2.2 函数RTC_EnterConfigMode2.3 函数RTC_ExitConfigMode2.4 函数RTC_GetCounter.2.5 函数RTC_SetCounter2.6 函数RTC_SetPrescaler2.7 函…...

ARMday04(开发版简介、LED点灯)

开发版简介 开发板为stm32MP157AAA,附加一个拓展版 硬件相关基础知识 PCB PCB&#xff08; Printed Circuit Board&#xff09;&#xff0c;中文名称为印制电路板&#xff0c;又称印刷线路板&#xff0c;是重要的电子部件&#xff0c;是电子元器件的支撑体&#xff0c;是电子…...

国际腾讯云:云服务器疑似被病毒入侵问题解决方案!!!

云服务器可能由于弱密码、开源组件漏洞的问题被黑客入侵&#xff0c;本文介绍如何判断云服务器是否被病毒入侵&#xff0c;及其解决方法。 问题定位 使用 SSH 方式 或 使用 VNC 方式 登录实例后&#xff0c;通过以下方式进行判断云服务器是否被病毒入侵&#xff1a; rc.loca…...

Perl语言用多线程爬取商品信息并做可视化处理

首先&#xff0c;我们需要使用Perl的LWP::UserAgent模块来发送HTTP请求。然后&#xff0c;我们可以使用HTML::TreeBuilder模块来解析HTML文档。在这个例子中&#xff0c;我们将使用BeautifulSoup模块来解析HTML文档。 #!/usr/bin/perl use strict; use warnings; use LWP::User…...

认识计算机-JavaEE初阶

文章目录 一、计算机的发展史二、冯诺依曼体系&#xff08;Von Neumann Architecture&#xff09;三、CPU基本工作流程3.1 算术逻辑单元&#xff08;ALU&#xff09;3.2 寄存器&#xff08;Register)和内存&#xff08;RAM&#xff09;3.3 控制单元&#xff08;CU&#xff09;3…...

you-get - 使用代码下载视频

文章目录 关于 you-get代码调用报错处理 源码简单分析 关于 you-get github : https://github.com/soimort/you-get you-get 是一个有名的开源视频下载工具包&#xff0c;这里不赘述。 代码调用 you-get 提供了命令行的方式下载视频&#xff0c;这里介绍使用 Python 调用源代…...

【Proteus仿真】【51单片机】汽车尾灯控制设计

文章目录 一、功能简介二、软件设计三、实验现象联系作者 一、功能简介 本项目使用Proteus8仿真51单片机控制器&#xff0c;使用按键、LED模块等。 主要功能&#xff1a; 系统运行后&#xff0c;系统运行后&#xff0c;系统开始运行&#xff0c;K1键控制左转向灯&#xff1b;…...

浙大恩特客户资源管理系统任意文件上传漏洞复现

0x01 产品简介 浙大恩特客户资源管理系统是一款针对企业客户资源管理的软件产品。该系统旨在帮助企业高效地管理和利用客户资源&#xff0c;提升销售和市场营销的效果。 0x02 漏洞概述 浙大恩特客户资源管理系统中fileupload.jsp接口处存在文件上传漏洞&#xff0c;未经身份认…...

史上第一款AOSP开发的IDE (支持Java/Kotlin/C++/Jni/Native/Shell/Python)

ASFP Study 史上第一款AOSP开发的IDE &#xff08;支持Java/Kotlin/C/Jni/Native/Shell/Python&#xff09; 类似于Android Studio&#xff0c;可用于开发Android系统源码。 Android studio for platform&#xff0c;简称asfp(爱上富婆)。 背景&下载&使用 背景 由…...

GCC + Vscode 搭建 nRF52xxx 开发环境

在 Windows 下使用 GCC Vscode 搭建 nRF52xxx 开发环境 ...... by 矜辰所致前言 最近有遇到项目需求&#xff0c;需要使用到 Nordic 的 nRF52xxx 芯片&#xff0c;还记得当初刚开始写博文的时候的写的 nRF52832 学习笔记&#xff0c;现在看当时笔记毫无逻辑可言&#xff0c…...

Linux应用开发基础知识——Framebuffer 应用编程(四)

前言&#xff1a; 在 Linux 系统中通过 Framebuffer 驱动程序来控制 LCD。Frame 是帧的意 思&#xff0c;buffer 是缓冲的意思&#xff0c;这意味着 Framebuffer 就是一块内存&#xff0c;里面保存着 一帧图像。Framebuffer 中保存着一帧图像的每一个像素颜色值&#xff0c;假设…...

智安网络|数据库入门秘籍:通俗易懂,轻松掌握与实践

在现代信息化时代&#xff0c;数据库已成为我们日常生活和工作中不可或缺的一部分。然而&#xff0c;对于非专业人士来说&#xff0c;数据库这个概念可能很抽象&#xff0c;难以理解。 一、什么是数据库&#xff1f; 简单来说&#xff0c;数据库是一个存储和管理数据的系统。它…...

EXCEL中安装多个vsto插件,插件之间互相影响功能,怎么解决

在 Excel 中安装多个 VSTO 插件&#xff0c;并且这些插件之间存在互相影响的情况下&#xff0c;可以采取以下措施来解决问题&#xff1a; 1. **隔离插件功能&#xff1a;** - 确保每个 VSTO 插件都有清晰的功能和责任范围&#xff0c;避免不同插件之间的功能重叠。这可以通…...

Java枚举

枚举类 概念 Java中的枚举&#xff08;Enumeration&#xff09;是一种特殊的数据类型&#xff0c;它是一种包含固定常量的类型。枚举是一种更加类型安全和更易维护的方式来定义常量&#xff0c;它包含了一组命名的值。 enum Weekday {MONDAY, TUESDAY, WEDNESDAY, THURSDAY,…...

基于MATLAB的关节型六轴机械臂轨迹规划仿真

笛卡尔空间下的轨迹规划&#xff0c;分为直线轨迹规划和圆弧轨迹规划&#xff0c;本文为笛卡尔空间下圆弧插值法的matlab仿真分析 目录 1 实验目的 2 实验内容 2.1标准D-H参数法 2.2实验中使用的Matlab函数 3 全部代码 4 仿真结果 1 实验目的 基于机器人学理论知识&…...

双11狂欢最后一天

大家好&#xff0c;本年度双11即将到来&#xff0c;为了答谢大家多年来的支持及更广泛的推广VBA的应用&#xff0c;“VBA语言専功”在此期间推出巨大优惠&#xff1a;此期间打包购买VBA技术资料实行半价优惠。 1&#xff1a;面向对象&#xff1a;学员及非学员 2&#xff1a;打…...

Unity3D中Gfx.WaitForPresent优化方案

前言 在Unity中&#xff0c;Gfx.WaitForPresent占用CPU过高通常表示主线程在等待GPU完成渲染&#xff08;即CPU被阻塞&#xff09;&#xff0c;这表明存在GPU瓶颈或垂直同步/帧率设置问题。以下是系统的优化方案&#xff1a; 对惹&#xff0c;这里有一个游戏开发交流小组&…...

在鸿蒙HarmonyOS 5中实现抖音风格的点赞功能

下面我将详细介绍如何使用HarmonyOS SDK在HarmonyOS 5中实现类似抖音的点赞功能&#xff0c;包括动画效果、数据同步和交互优化。 1. 基础点赞功能实现 1.1 创建数据模型 // VideoModel.ets export class VideoModel {id: string "";title: string ""…...

智能在线客服平台:数字化时代企业连接用户的 AI 中枢

随着互联网技术的飞速发展&#xff0c;消费者期望能够随时随地与企业进行交流。在线客服平台作为连接企业与客户的重要桥梁&#xff0c;不仅优化了客户体验&#xff0c;还提升了企业的服务效率和市场竞争力。本文将探讨在线客服平台的重要性、技术进展、实际应用&#xff0c;并…...

微信小程序 - 手机震动

一、界面 <button type"primary" bindtap"shortVibrate">短震动</button> <button type"primary" bindtap"longVibrate">长震动</button> 二、js逻辑代码 注&#xff1a;文档 https://developers.weixin.qq…...

1.3 VSCode安装与环境配置

进入网址Visual Studio Code - Code Editing. Redefined下载.deb文件&#xff0c;然后打开终端&#xff0c;进入下载文件夹&#xff0c;键入命令 sudo dpkg -i code_1.100.3-1748872405_amd64.deb 在终端键入命令code即启动vscode 需要安装插件列表 1.Chinese简化 2.ros …...

让AI看见世界:MCP协议与服务器的工作原理

让AI看见世界&#xff1a;MCP协议与服务器的工作原理 MCP&#xff08;Model Context Protocol&#xff09;是一种创新的通信协议&#xff0c;旨在让大型语言模型能够安全、高效地与外部资源进行交互。在AI技术快速发展的今天&#xff0c;MCP正成为连接AI与现实世界的重要桥梁。…...

CMake控制VS2022项目文件分组

我们可以通过 CMake 控制源文件的组织结构,使它们在 VS 解决方案资源管理器中以“组”(Filter)的形式进行分类展示。 🎯 目标 通过 CMake 脚本将 .cpp、.h 等源文件分组显示在 Visual Studio 2022 的解决方案资源管理器中。 ✅ 支持的方法汇总(共4种) 方法描述是否推荐…...

听写流程自动化实践,轻量级教育辅助

随着智能教育工具的发展&#xff0c;越来越多的传统学习方式正在被数字化、自动化所优化。听写作为语文、英语等学科中重要的基础训练形式&#xff0c;也迎来了更高效的解决方案。 这是一款轻量但功能强大的听写辅助工具。它是基于本地词库与可选在线语音引擎构建&#xff0c;…...

PAN/FPN

import torch import torch.nn as nn import torch.nn.functional as F import mathclass LowResQueryHighResKVAttention(nn.Module):"""方案 1: 低分辨率特征 (Query) 查询高分辨率特征 (Key, Value).输出分辨率与低分辨率输入相同。"""def __…...

Linux nano命令的基本使用

参考资料 GNU nanoを使いこなすnano基础 目录 一. 简介二. 文件打开2.1 普通方式打开文件2.2 只读方式打开文件 三. 文件查看3.1 打开文件时&#xff0c;显示行号3.2 翻页查看 四. 文件编辑4.1 Ctrl K 复制 和 Ctrl U 粘贴4.2 Alt/Esc U 撤回 五. 文件保存与退出5.1 Ctrl …...