龙源期刊网 http://www.qikan.com.cn
基于Java synchronized同步锁实现线程交互
作者:崔政 段利国
来源:《软件工程》2018年第02期
摘 要:Java多线程能够提高CPU利用效率,但也容易造成线程不安全、线程死锁等问题。本文详细介绍了Java线程各状态之间的关系及其切换,并用实例展示了使用同步锁synchronized保证同一时刻只有一个线程操作同一资源,使用wait()、notify()切换线程状态保证线程操作的前后顺序实现线程交互。理解Java线程各状态之间的关系及其切换,能帮助用户在使用Java多线程的场景有效避免多线程带来的不安全问题。 关键词:多线程;synchronized;线程交互 中图分类号:TP312 文献标识码:A
Abstract:Java multi-threading can improve CPU utilization,but it can also cause problems such as thread insecurity and thread deadlock.This paper introduces in detail the relationship between Java thread states and their transitions.Java synchronized ensures that only one thread operates the same resource at the same time,using wait() and notify() to switch the thread state to ensure that thread interactions are implemented in the context of thread operations.Understanding the
relationship between the states of Java threads and their switching can help users avoid effectively the unsafe problems of multi-threading in Java multi-threaded scenarios. Keywords:multi-threading;synchronized;thread interaction 1 引言(Introduction)
Java多线程的使用提高了CPU的利用效率[1-3],能够带来更好的用户体验。但是不当的线程使用可能会引起线程不安全,不能显示用户想要的结果,甚至造成线程死锁[4,5],存在程序无法执行等缺点。充分理解Java线程各状态之间的关系及其切换,能够在各种需要使用Java多线程的场景有效避免多线程带来的不安全问题。本文首先介绍Java创建线程的两种方式,接着介绍线程各状态之间的关系及其切换,最后使用synchronized、wait()和notify()实现线程交互。
2 Java创建线程的方式(The way Java creates threads)