A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

本帖最后由 wuqiong 于 2018-6-7 16:24 编辑

1-4、注意synchronized关键字的使用

在前面的文章中我们主要讲解的是线程中“对象锁”的工作原理和操作方式。在讲解synchronized关键字的时候,我们还提到了synchronized关键字可以标注的位置。大家经常看到相当部分的网贴,在它们的代码示例中将synchronized关键字加载到代码的方法体上,然后告诉读者:这个操作是线程安全的。代码可能如下:

但事实上,一个对象是否是线程安全的除了添加synchronized关键字以外,更重要的还要看如何进行这个对象的操作。如下代码中,我们展示了在两个线程的doOtherthing方法(所谓的线程安全方法),去操作一个对象NOWVALUE:

所以,一个对象是否是线程安全的除了添加synchronized关键字以外,更重要的还要看如何进行这个对象的操作;标注了synchronized关键字的方法中,针对某个对象的操作不一定是线程安全的!

2、JAVA中的基本线程操作

这是前文中已经给出的线程状态切换图例,可能有的读者还不能完全理解其中的切换条件,没关系从本章节开始我们将详细介绍JAVA中如何进行这些线程状态的操作。

除了上一章节在讲解“对象锁”的时候已经提到的wait、wait(time)操作以外,本章节将讲解notify、notifyAll、interrupt、join和sleep等操作。

2-1、notify和notifyAll操作

在JAVA JDK中,对于notify方法和notifyAll方法的解释分别是:

  • notify:

Wakes up a single thread that is waiting on this object’s monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object’s monitor by calling one of the wait methods.

The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object. The awakened thread will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened thread enjoys no reliable privilege or disadvantage in being the next thread to lock this object.

  • notifyAll:

Wakes up all threads that are waiting on this object’s monitor. A thread waits on an object’s monitor by calling one of the wait methods.

The awakened threads will not be able to proceed until the current thread relinquishes the lock on this object. The awakened threads will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened threads enjoy no reliable privilege or disadvantage in being the next thread to lock this object.

为了说明notify方法和notifyAll方法的工作现象,下面我会为这两个方法分别给出一段代码,并进行详细解释。

2-1-1、notify方法的工作情况
  • ParentNotifyThread类:

  • ChildNotifyThread类:

以上两段代码中,ParentNotifyThread类负责创建三个ChildNotifyThread类的对象,每一个ChildNotifyThread类的实例对象都持有ParentNotifyThread.WAIT_CHILEOBJECT对象的“钥匙”,并通过wait方法退出ParentNotifyThread.WAIT_CHILEOBJECT对象的独占状态(但是不归还锁),如下图所示:


然后我们通过ParentNotifyThread类中的ParentNotifyThread.WAIT_CHILEOBJECT.notify()方法解除阻塞状态:

然后我们观察代码的执行结果:

(接下文)


2 个回复

倒序浏览
加油加油
回复 使用道具 举报
666666
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马