首先回顾一下我们的基础知识。

sleep:

  线程睡眠,不会释放锁

wait:

  线程等待。释放锁。

notity:

  唤醒随机一个当前对象等待的线程,并不会释放锁

notityAll:

  唤醒所有当前对象等待的线程,并不会释放锁

遇到问题:

  代码如下:

  

package com.zhen.ten_chapter.question;

/**
* @author zhen
* @Date 2019/4/18 10:17
*/
public class ThreadDemo {
public static void main(String[] args) {
To10X tos = new To10X(1, 10);
tos.start();
int res = tos.getResult();
System.out.println(res); } static class To10X extends Thread { private int point = 1;
private int end = 10; private int result = 0; public To10X(int start, int end) {
this.point = start;
this.end = end; } @Override
public synchronized void run() { while (point != end + 1) {
result += point++;
System.out.println(Thread.currentThread().getName() + "::" + result);
}
this.notify();
} public synchronized int getResult() { while(result == 0) {
try {
System.out.println("锁定前");
this.wait();
System.out.println("锁定后");
} catch (Exception e) {
e.printStackTrace();
}
} return result;
}
}
}

  程序发现wait总是会被唤醒。

  怀疑是不是总是先wait然后再被notity了,于是将notify注释掉了,但依然被唤醒。

什么原因?

  我关注点放在了static关键字上了,依稀记得static 方法的锁锁对象是类,那么static类里面的成员方法的锁对象是不是也是类呢?

    当然是我多想了,但是我依然将static 的内部类改为了一个普通内部类,然后用实例化对象去创建的对应对象与执行方法。可是结果依旧是一样。

  我接下来怀疑是主线程的原因

      因为其他线程都是从主线程上衍生出来的,线程不是很熟练,依稀记得一些所谓守护线程等概念。于是简单写了一个Demo类,主线程wait,然后开一个线程获取到锁执行到结束,然后发现能wait住主线程

那是什么原因呢?

  接下来我觉得一定是有什么东西唤醒了主线程,notity被我注释掉了,notityAll没有编写。查看wait的api,发现它没有自动唤醒的说法,有一个参数是延迟等待的意思。它明确声明了只能靠notity和notifyAll唤醒。百度大法好。我狂百度,发现有人遇到和我一样的问题,参考链接:  https://blog.csdn.net/nmyangym/article/details/7850882#commentBox 。为此,我也去看了一下所谓的jdk的Thread类的join源码,如下:

  public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0; if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
} if (millis == 0) {
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}

  它确实调用了wait,但是调用了wait能保证唤醒吗?我感觉方向没问题了,继续针对点去百度

参考链接:

  https://segmentfault.com/q/1010000016744022?utm_source=tag-newest

  原来,Thread对象在线程结束的时候,会自动调用一次notifyAll语法,线程结束会执行join方法,join的jdk写法我们看到过,大牛给出的依据是openJDK中的源码:

int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread);

static void *java_start(Thread *thread) {
...
thread->run();
return 0;
} void JavaThread::run() {
...
thread_main_inner();
} void JavaThread::thread_main_inner() {
...
this->exit(false);
delete this;
} void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
...
// Notify waiters on thread object. This has to be done after exit() is called
// on the thread (if the thread is the last thread in a daemon ThreadGroup the
// group should have the destroyed bit set before waiters are notified).
ensure_join(this);
...
} static void ensure_join(JavaThread* thread) {
// We do not need to grap the Threads_lock, since we are operating on ourself.
Handle threadObj(thread, thread->threadObj());
assert(threadObj.not_null(), "java thread object must exist");
ObjectLocker lock(threadObj, thread);
// Ignore pending exception (ThreadDeath), since we are exiting anyway
thread->clear_pending_exception();
// Thread is exiting. So set thread_status field in java.lang.Thread class to TERMINATED.
java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED);
// Clear the native thread instance - this makes isAlive return false and allows the join()
// to complete once we've done the notify_all below
java_lang_Thread::set_thread(threadObj(), NULL);
lock.notify_all(thread);
// Ignore pending exception (ThreadDeath), since we are exiting anyway
thread->clear_pending_exception();
}

  

 

结论:

  尽量不要用线程对象做同步锁的钥匙,线程结束的时候它会自动调用this.notifyAll()

Thread类线程结束会唤醒使用其对象做锁而睡眠的线程的更多相关文章

  1. java基础知识回顾之java Thread类学习(四)--java多线程安全问题(锁)

    上一节售票系统中我们发现,打印出了错票,0,-1,出现了多线程安全问题.我们分析为什么会发生多线程安全问题? 看下面线程的主要代码: @Override public void run() { // ...

  2. java基础知识回顾之java Thread类学习(五)--java多线程安全问题(锁)同步的前提

    这里举个例子讲解,同步synchronized在什么地方加,以及同步的前提: * 1.必须要有两个以上的线程,才需要同步. * 2.必须是多个线程使用同一个锁. * 3.必须保证同步中只能有一个线程在 ...

  3. Java多线程系列--“基础篇”05之 线程等待与唤醒

    概要 本章,会对线程等待/唤醒方法进行介绍.涉及到的内容包括:1. wait(), notify(), notifyAll()等方法介绍2. wait()和notify()3. wait(long t ...

  4. java 多线程—— 线程等待与唤醒

    java 多线程 目录: Java 多线程——基础知识 Java 多线程 —— synchronized关键字 java 多线程——一个定时调度的例子 java 多线程——quartz 定时调度的例子 ...

  5. Java多线程5:线程等待与唤醒

    原文:http://www.cnblogs.com/skywang12345/p/3479224.html wait(),notify(), notifyAll()等方法介绍在Object.java中 ...

  6. Java多线程(五)——线程等待与唤醒

    一.wait().notify().notifyAll()等方法介绍 在Object.java中,定义了wait(), notify()和notifyAll()等接口.wait()的作用是让当前线程进 ...

  7. java - 线程等待与唤醒

    Java多线程系列--“基础篇”05之 线程等待与唤醒 概要 本章,会对线程等待/唤醒方法进行介绍.涉及到的内容包括:1. wait(), notify(), notifyAll()等方法介绍2. w ...

  8. java 多线程系列基础篇(五)之线程等待与唤醒

    1.wait(), notify(), notifyAll()等方法介绍 在Object.java中,定义了wait(), notify()和notifyAll()等接口.wait()的作用是让当前线 ...

  9. Java 多线程基础(六)线程等待与唤醒

    Java 多线程基础(六)线程等待与唤醒 遇到这样一个场景,当某线程里面的逻辑需要等待异步处理结果返回后才能继续执行.或者说想要把一个异步的操作封装成一个同步的过程.这里就用到了线程等待唤醒机制. 一 ...

随机推荐

  1. Clover 安装 Mac 系统更新 (原版黑苹果)

    关于使用原版镜像(即 .dmg )安装黑苹果的升级,笔者写写自身经验吧. 在Clover启动的界面中与Mac OS有关的启动菜单有以下这些: Boot FileVault Prebooter from ...

  2. Table组件设置文字超出宽度显示省略号,鼠标悬停以悬浮框显示

    一.设置文字超出宽度显示省略号 注意点: 1.  需要指定column的width属性,否则列头跟内容可能不对齐.需要留一列不设置宽度以适应弹性布局. 2. 列宽度width必须大于ellipsis的 ...

  3. PHP curl Post请求和Get请求~

    //获取的参数 $api_key = '8a82d53a57b06c1d835d129f7e43d49c'; $orderNum = pdo_fetch('select ddlm_order_no f ...

  4. TP5创建动态数据表

    $sql = " CREATE TABLE IF NOT EXISTS `$table_name` (`id` int(11) unsigned NOT NULL AUTO_INCREMEN ...

  5. Unity3d外包公司|UE4外包公司:谷歌首款Daydream VR设备上手

    这款售价仅为79美元(约合人民币525元)的产品内含“够用”的手柄和一台头戴设备,只要你有一台支持月日,10月5日,dream平台的手机(未来将成为安卓平台的标配),就能体验VR的乐趣. 即使该产品最 ...

  6. [python]Git

    Git 修改默认编辑器 git config –global core.editor vim 提交发生变化得文件 # 提交新文件(new)和被修改(modified)文件,不包括被删除(deleted ...

  7. hsy单词

    题意:略 在ac自动机上,一个节点出现的次数等于能通过fail到它的节点的次数之和.而叶节点就等于它被爬过的次数. #include <iostream> #include <cst ...

  8. selenium chromedriver geckodriver iedriverserver下载

    chromedriver与chrome的的对应版整理: chromedriver版本 chrome版本 v2.9 v31-v34 v2.10 v33-v36 v2.11 v36-v40 v2.12 v ...

  9. [tomcat] tomcat简析(一)

    1.Tomcat的顶层结构 Tomcat中最顶层的容器叫Server,代表整个服务器,Server中包含至少一个Service,用于 具体提供服务. Service主要包含两部分:Connector和 ...

  10. [luogu P3960] [noip2017 d2t3] 队列

    [luogu P3960] [noip2017 d2t3] 队列 题目描述 Sylvia 是一个热爱学习的女♂孩子. 前段时间,Sylvia 参加了学校的军训.众所周知,军训的时候需要站方阵. Syl ...