当前位置: 首页 > 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;打…...

多模态2025:技术路线“神仙打架”,视频生成冲上云霄

文&#xff5c;魏琳华 编&#xff5c;王一粟 一场大会&#xff0c;聚集了中国多模态大模型的“半壁江山”。 智源大会2025为期两天的论坛中&#xff0c;汇集了学界、创业公司和大厂等三方的热门选手&#xff0c;关于多模态的集中讨论达到了前所未有的热度。其中&#xff0c;…...

抖音增长新引擎:品融电商,一站式全案代运营领跑者

抖音增长新引擎&#xff1a;品融电商&#xff0c;一站式全案代运营领跑者 在抖音这个日活超7亿的流量汪洋中&#xff0c;品牌如何破浪前行&#xff1f;自建团队成本高、效果难控&#xff1b;碎片化运营又难成合力——这正是许多企业面临的增长困局。品融电商以「抖音全案代运营…...

unix/linux,sudo,其发展历程详细时间线、由来、历史背景

sudo 的诞生和演化,本身就是一部 Unix/Linux 系统管理哲学变迁的微缩史。来,让我们拨开时间的迷雾,一同探寻 sudo 那波澜壮阔(也颇为实用主义)的发展历程。 历史背景:su的时代与困境 ( 20 世纪 70 年代 - 80 年代初) 在 sudo 出现之前,Unix 系统管理员和需要特权操作的…...

拉力测试cuda pytorch 把 4070显卡拉满

import torch import timedef stress_test_gpu(matrix_size16384, duration300):"""对GPU进行压力测试&#xff0c;通过持续的矩阵乘法来最大化GPU利用率参数:matrix_size: 矩阵维度大小&#xff0c;增大可提高计算复杂度duration: 测试持续时间&#xff08;秒&…...

LangChain知识库管理后端接口:数据库操作详解—— 构建本地知识库系统的基础《二》

这段 Python 代码是一个完整的 知识库数据库操作模块&#xff0c;用于对本地知识库系统中的知识库进行增删改查&#xff08;CRUD&#xff09;操作。它基于 SQLAlchemy ORM 框架 和一个自定义的装饰器 with_session 实现数据库会话管理。 &#x1f4d8; 一、整体功能概述 该模块…...

2025年- H71-Lc179--39.组合总和(回溯,组合)--Java版

1.题目描述 2.思路 当前的元素可以重复使用。 &#xff08;1&#xff09;确定回溯算法函数的参数和返回值&#xff08;一般是void类型&#xff09; &#xff08;2&#xff09;因为是用递归实现的&#xff0c;所以我们要确定终止条件 &#xff08;3&#xff09;单层搜索逻辑 二…...

ubuntu中安装conda的后遗症

缘由: 在编译rk3588的sdk时&#xff0c;遇到编译buildroot失败&#xff0c;提示如下&#xff1a; 提示缺失expect&#xff0c;但是实测相关工具是在的&#xff0c;如下显示&#xff1a; 然后查找借助各个ai工具&#xff0c;重新安装相关的工具&#xff0c;依然无解。 解决&am…...

RFID推动新能源汽车零部件生产系统管理应用案例

RFID推动新能源汽车零部件生产系统管理应用案例 一、项目背景 新能源汽车零部件场景 在新能源汽车零部件生产领域&#xff0c;电子冷却水泵等关键部件的装配溯源需求日益增长。传统 RFID 溯源方案采用 “网关 RFID 读写头” 模式&#xff0c;存在单点位单独头溯源、网关布线…...

[C++错误经验]case语句跳过变量初始化

标题&#xff1a;[C错误经验]case语句跳过变量初始化 水墨不写bug 文章目录 一、错误信息复现二、错误分析三、解决方法 一、错误信息复现 write.cc:80:14: error: jump to case label80 | case 2:| ^ write.cc:76:20: note: crosses initialization…...

Redis专题-实战篇一-基于Session和Redis实现登录业务

GitHub项目地址&#xff1a;https://github.com/whltaoin/redisLearningProject_hm-dianping 基于Session实现登录业务功能提交版本码&#xff1a;e34399f 基于Redis实现登录业务提交版本码&#xff1a;60bf740 一、导入黑马点评后端项目 项目架构图 1. 前期阶段2. 后续阶段导…...