热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

java多线程线程安全_Java中的线程安全

java多线程线程安全ThreadSafetyinJavaisaveryimportanttopic.Javaprovidesmulti-threadedenvironmentsu

java多线程 线程安全

Thread Safety in Java is a very important topic. Java provides multi-threaded environment support using Java Threads, we know that multiple threads created from same Object share object variables and this can lead to data inconsistency when the threads are used to read and update the shared data.

Java中的线程安全是一个非常重要的主题。 Java使用Java线程提供了多线程环境支持,我们知道从同一个对象创建的多个线程共享对象变量,当这些线程用于读取和更新共享数据时,这可能导致数据不一致

线程安全 (Thread Safety)

thread safe, thread safety, thread safety in java, thread safe java

The reason for data inconsistency is because updating any field value is not an atomic process, it requires three steps; first to read the current value, second to do the necessary operations to get the updated value and third to assign the updated value to the field reference.


数据不一致的原因是因为更新任何字段值都不是原子过程,它需要三个步骤。 首先读取当前值,其次进行必要的操作以获取更新的值,第三次将更新的值分配给字段引用。

Let’s check this with a simple program where multiple threads are updating the shared data.

让我们用一个简单的程序检查一下,其中多个线程正在更新共享数据。

package com.journaldev.threads;public class ThreadSafety {public static void main(String[] args) throws InterruptedException {ProcessingThread pt &#61; new ProcessingThread();Thread t1 &#61; new Thread(pt, "t1");t1.start();Thread t2 &#61; new Thread(pt, "t2");t2.start();//wait for threads to finish processingt1.join();t2.join();System.out.println("Processing count&#61;"&#43;pt.getCount());}}class ProcessingThread implements Runnable{private int count;&#64;Overridepublic void run() {for(int i&#61;1; i <5; i&#43;&#43;){processSomething(i);count&#43;&#43;;}}public int getCount() {return this.count;}private void processSomething(int i) {// processing some jobtry {Thread.sleep(i*1000);} catch (InterruptedException e) {e.printStackTrace();}}}

In the above program for loop, count is incremented by 1 four times and since we have two threads, its value should be 8 after both the threads finished executing. But when you will run the above program multiple times, you will notice that count value is varying between 6,7,8. This is happening because even if count&#43;&#43; seems to be an atomic operation, its NOT and causing data corruption.

在上面的for循环程序中&#xff0c; count增加1到四倍&#xff0c;并且由于我们有两个线程&#xff0c;因此两个线程执行完后其值应为8。 但是当您多次运行上述程序时&#xff0c;您会注意到计数值在6,7,8之间变化。 发生这种情况是因为即使count &#43;&#43;似乎是一个原子操作&#xff0c;它的NOT也不会导致数据损坏。

Java中的线程安全 (Thread Safety in Java)

Thread safety in java is the process to make our program safe to use in multithreaded environment, there are different ways through which we can make our program thread safe.

Java中的线程安全是使我们的程序在多线程环境中可以安全使用的过程&#xff0c;可以通过多种方法使程序线程安全。

  • Synchronization is the easiest and most widely used tool for thread safety in java.

    同步是Java中线程安全最简单&#xff0c;使用最广泛的工具。
  • Use of Atomic Wrapper classes from java.util.concurrent.atomic package. For example AtomicInteger

    java.util.concurrent.atomic包使用Atomic Wrapper类。 例如AtomicInteger
  • Use of locks from java.util.concurrent.locks package.

    使用java.util.concurrent.locks包中的锁。
  • Using thread safe collection classes, check this post for usage of ConcurrentHashMap for thread safety.

    使用线程安全收集类&#xff0c;请检查此帖子以了解ConcurrentHashMap的线程安全用法。
  • Using volatile keyword with variables to make every thread read the data from memory, not read from thread cache.

    将volatile关键字与变量一起使用&#xff0c;可使每个线程从内存中读取数据&#xff0c;而不是从线程缓存中读取数据。

Java同步 (Java synchronized)

Synchronization is the tool using which we can achieve thread-safety, JVM guarantees that synchronized code will be executed by only one thread at a time. java keyword synchronized is used to create synchronized code and internally it uses locks on Object or Class to make sure only one thread is executing the synchronized code.

同步是我们可以用来实现线程安全性的工具&#xff0c;JVM保证同步的代码一次只能由一个线程执行。 java关键字sync用于创建同步代码&#xff0c;并且在内部使用Object或Class上的锁来确保只有一个线程在执行同步代码。

  • Java synchronization works on locking and unlocking of the resource before any thread enters into synchronized code, it has to acquire the lock on the Object and when code execution ends, it unlocks the resource that can be locked by other threads. In the meantime, other threads are in wait state to lock the synchronized resource.

    Java同步可在任何线程进入同步代码之前对资源进行锁定和解锁&#xff0c;它必须获得对Object的锁定&#xff0c;并且在代码执行结束时&#xff0c;它会解锁可以被其他线程锁定的资源。 同时&#xff0c;其他线程处于等待状态以锁定同步资源。
  • We can use synchronized keyword in two ways, one is to make a complete method synchronized and another way is to create synchronized block.

    我们可以通过两种方式使用synced关键字&#xff0c;一种是使完整的方法同步&#xff0c;另一种方法是创建同步块。
  • When a method is synchronized, it locks the Object, if method is static it locks the Class, so it’s always best practice to use synchronized block to lock the only sections of method that needs synchronization.

    同步方法时&#xff0c;它会锁定Object &#xff1b;如果方法是静态的&#xff0c;则它会锁定Class &#xff0c;因此&#xff0c;最佳做法始终是使用同步块来锁定方法中仅需要同步的部分。
  • While creating a synchronized block, we need to provide the resource on which lock will be acquired, it can be XYZ.class or any Object field of the class.

    创建同步块时&#xff0c;我们需要提供获取锁定的资源&#xff0c;它可以是XYZ.class或该类的任何Object字段。
  • synchronized(this) will lock the Object before entering into the synchronized block.

    synchronized(this)将在进入同步块之前锁定对象。
  • You should use the lowest level of locking, for example, if there are multiple synchronized block in a class and one of them is locking the Object, then other synchronized blocks will also be not available for execution by other threads. When we lock an Object, it acquires a lock on all the fields of the Object.

    您应该使用最低级别的锁定 &#xff0c;例如&#xff0c;如果一个类中有多个同步块&#xff0c;而其中一个正在锁定Object&#xff0c;则其他同步块也将不可用于其他线程执行。 当我们锁定一个对象时&#xff0c;它获得了对该对象所有字段的锁定。
  • Java Synchronization provides data integrity on the cost of performance, so it should be used only when it’s absolutely necessary.

    Java同步以性能为代价提供数据完整性&#xff0c;因此仅在绝对必要时才应使用它。
  • Java Synchronization works only in the same JVM, so if you need to lock some resource in multiple JVM environment, it will not work and you might have to look after some global locking mechanism.

    Java同步仅在同一个JVM中起作用&#xff0c;因此&#xff0c;如果您需要在多个JVM环境中锁定某些资源&#xff0c;则它将无法正常工作&#xff0c;因此您可能需要照顾一些全局锁定机制。
  • Java Synchronization could result in deadlocks, check this post about deadlock in java and how to avoid them.

    Java同步可能会导致死锁&#xff0c;请查看有关Java死锁以及如何避免死锁的文章。
  • Java synchronized keyword cannot be used for constructors and variables.

    Java同步关键字不能用于构造函数和变量。
  • It is preferable to create a dummy private Object to use for the synchronized block so that it’s reference can’t be changed by any other code. For example, if you have a setter method for Object on which you are synchronizing, it’s reference can be changed by some other code leads to the parallel execution of the synchronized block.

    最好创建一个虚拟私有对象用于同步块&#xff0c;以使它的引用不能被任何其他代码更改。 例如&#xff0c;如果您有一个要在其上同步的Object的setter方法&#xff0c;则可以通过其他一些代码来更改其引用&#xff0c;从而导致并行执行同步块。
  • We should not use any object that is maintained in a constant pool, for example String should not be used for synchronization because if any other code is also locking on same String, it will try to acquire lock on the same reference object from String pool and even though both the codes are unrelated, they will lock each other.

    我们不应该使用在常量池中维护的任何对象&#xff0c;例如&#xff0c;不应将String用于同步&#xff0c;因为如果任何其他代码也锁定在同一String上&#xff0c;它将尝试从String池获取对同一引用对象的锁定&#xff0c;并且即使两个代码无关&#xff0c;它们也会互相锁定。

Here are the code changes we need to do in the above program to make it thread-safe.

这是我们在上述程序中需要执行的代码更改&#xff0c;以使其具有线程安全性。

//dummy object variable for synchronizationprivate Object mutex&#61;new Object();...//using synchronized block to read, increment and update count value synchronouslysynchronized (mutex) {count&#43;&#43;;}

Let’s see some synchronization examples and what can we learn from them.

让我们看看一些同步示例&#xff0c;以及我们可以从中学到什么。

public class MyObject {// Locks on the object&#39;s monitorpublic synchronized void doSomething() { // ...}
}// Hackers code
MyObject myObject &#61; new MyObject();
synchronized (myObject) {while (true) {// Indefinitely delay myObjectThread.sleep(Integer.MAX_VALUE); }
}

Notice that hacker’s code is trying to lock the myObject instance and once it gets the lock, it’s never releasing it causing doSomething() method to block on waiting for the lock, this will cause the system to go on deadlock and cause Denial of Service (DoS).

请注意&#xff0c;黑客的代码正在尝试锁定myObject实例&#xff0c;并且一旦获得了锁定&#xff0c;就永远不会释放它&#xff0c;从而导致doSomething&#xff08;&#xff09;方法在等待锁定时阻塞&#xff0c;这将导致系统进入死锁并导致拒绝服务&#xff08; DoS&#xff09;。

public class MyObject {public Object lock &#61; new Object();public void doSomething() {synchronized (lock) {// ...}}
}//untrusted codeMyObject myObject &#61; new MyObject();
//change the lock Object reference
myObject.lock &#61; new Object();

Notice that lock Object is public and by changing its reference, we can execute synchronized block parallel in multiple threads. A similar case is true if you have private Object but have a setter method to change its reference.

注意&#xff0c;锁对象是公共的&#xff0c;并且通过更改其引用&#xff0c;我们可以在多个线程中并行执行同步块。 如果您有私有Object但有一个setter方法来更改其引用&#xff0c;则情况类似。

public class MyObject {//locks on the class object&#39;s monitorpublic static synchronized void doSomething() { // ...}
}// hackers code
synchronized (MyObject.class) {while (true) {Thread.sleep(Integer.MAX_VALUE); // Indefinitely delay MyObject}
}

Notice that hacker code is getting a lock on the class monitor and not releasing it, it will cause deadlock and DoS in the system.

请注意&#xff0c;黑客代码已在类监视器上获得锁定&#xff0c;而没有释放它&#xff0c;这将导致系统中的死锁和DoS。

Here is another example where multiple threads are working on the same array of Strings and once processed, appending thread name to the array value.

这是另一个示例&#xff0c;其中多个线程正在相同的String数组上工作&#xff0c;并且一旦被处理&#xff0c;就将线程名附加到数组值中。

package com.journaldev.threads;import java.util.Arrays;public class SyncronizedMethod {public static void main(String[] args) throws InterruptedException {String[] arr &#61; {"1","2","3","4","5","6"};HashMapProcessor hmp &#61; new HashMapProcessor(arr);Thread t1&#61;new Thread(hmp, "t1");Thread t2&#61;new Thread(hmp, "t2");Thread t3&#61;new Thread(hmp, "t3");long start &#61; System.currentTimeMillis();//start all the threadst1.start();t2.start();t3.start();//wait for threads to finisht1.join();t2.join();t3.join();System.out.println("Time taken&#61; "&#43;(System.currentTimeMillis()-start));//check the shared variable value nowSystem.out.println(Arrays.asList(hmp.getMap()));}}class HashMapProcessor implements Runnable{private String[] strArr &#61; null;public HashMapProcessor(String[] m){this.strArr&#61;m;}public String[] getMap() {return strArr;}&#64;Overridepublic void run() {processArr(Thread.currentThread().getName());}private void processArr(String name) {for(int i&#61;0; i

Here is the output when I run the above program.

这是我运行上述程序时的输出。

Time taken&#61; 15005
[1:t2:t3, 2:t1, 3:t3, 4:t1:t3, 5:t2:t1, 6:t3]

The String array values are corrupted because of shared data and no synchronization. Here is how we can change addThreadName() method to make our program thread-safe.

由于共享数据且没有同步&#xff0c;因此String数组值已损坏。 这是我们如何更改addThreadName&#xff08;&#xff09;方法以使程序具有线程安全性的方法。

private Object lock &#61; new Object();private void addThreadName(int i, String name) {synchronized(lock){strArr[i] &#61; strArr[i] &#43;":"&#43;name;}}

After this change, our program works fine and here is the correct output of the program.

进行此更改后&#xff0c;我们的程序可以正常工作&#xff0c;这是程序的正确输出。

Time taken&#61; 15004
[1:t1:t2:t3, 2:t2:t1:t3, 3:t2:t3:t1, 4:t3:t2:t1, 5:t2:t1:t3, 6:t2:t1:t3]

That’s all for thread safety in java, I hope you learned about thread-safe programming and using synchronized keyword.

这就是Java中线程安全的全部内容&#xff0c;希望您了解线程安全编程以及如何使用synced关键字。

翻译自: https://www.journaldev.com/1061/thread-safety-in-java

java多线程 线程安全



推荐阅读
  • 本文介绍了两种使用Java发送短信的方法:利用第三方平台的HTTP请求和通过硬件设备短信猫。重点讲解了如何通过Java代码配置和使用短信猫发送短信的过程,包括必要的编码转换、串口操作及短信发送的核心逻辑。 ... [详细]
  • Spring Boot 入门指南
    本文介绍了Spring Boot的基本概念及其在现代Java应用程序开发中的作用。Spring Boot旨在简化Spring应用的初始设置和开发过程,通过自动配置和约定优于配置的原则,帮助开发者快速构建基于Spring框架的应用。 ... [详细]
  • 本文介绍了Java中使用线程池执行器(ExecutorService)来管理和调度多线程任务的方法。通过具体的代码示例,详细解释了不同类型的线程池创建方式及其应用场景。 ... [详细]
  • Eclipse 下 JavaFX 程序开发指南
    本文介绍了 JavaFX,这是一个用于创建富客户端应用程序的 Java 图形和媒体工具包,并详细说明了如何在 Eclipse 环境中配置和开发 JavaFX 应用。 ... [详细]
  • 深入理解设计模式之观察者模式
    本文详细介绍了观察者模式,这是一种行为设计模式,适用于当对象状态发生变化时,需要通知其他相关对象的场景。文中不仅解释了观察者模式的基本概念,还通过Java代码示例展示了其实现方法。 ... [详细]
  • 本文探讨了Java中char数据类型的特点,包括其表示范围以及如何处理超出16位字符限制的情况。通过引入代码点和代码单元的概念,详细解释了Java处理增补字符的方法。 ... [详细]
  • 本文将详细介绍NSRunLoop的工作原理,包括其基本概念、消息类型(事件源)、运行模式、生命周期管理以及嵌套运行等关键知识点,帮助开发者更好地理解和应用这一重要技术。 ... [详细]
  • 主板市盈率、市净率及股息率的自动化抓取
    本文介绍了如何通过Python脚本自动从中国指数有限公司网站抓取主板的市盈率、市净率和股息率等关键财务指标,并将这些数据存储到CSV文件中。涉及的技术包括网页解析、正则表达式以及异常处理。 ... [详细]
  • 本文探讨了在渗透测试中信息收集阶段使用的几种端口扫描技术,包括nmap、masscan、socket、telnet及nc等工具的应用与比较。 ... [详细]
  • 本文探讨了如何在 Spring 3 MVC 应用程序中配置 MySQL 数据库连接,通过 XML 配置实现 JDBC 直接操作数据库,而不使用 Hibernate 等额外框架。 ... [详细]
  • Python多线程编程详解
    本文深入探讨了Python中的多线程机制,包括线程的基本概念、创建线程的方法以及线程间的通信策略。 ... [详细]
  • 单例模式是软件开发中常用的设计模式之一,用于确保一个类只有一个实例,并提供一个全局访问点。本文探讨了在单例模式实现中使用volatile关键字的重要性,特别是在懒汉模式下的应用。 ... [详细]
  • Webpack中实现环境与代码的有效分离
    本文探讨了如何在Webpack中有效地区分开发与生产环境,并实现代码的合理分离,以提高项目的可维护性和加载性能。 ... [详细]
  • addcslashes—以C语言风格使用反斜线转义字符串中的字符addslashes—使用反斜线引用字符串bin2hex—函数把包含数据的二进制字符串转换为十六进制值chop—rt ... [详细]
  • 本文探讨了在 Xamarin 表单中使用 .NET Standard 2.0 库时遇到的兼容性问题及解决方案。 ... [详细]
author-avatar
手机用户2502910213
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有