资讯专栏INFORMATION COLUMN

Java并发编程——线程基础查漏补缺

luqiuwen / 1540人阅读

摘要:告诉当前执行的线程为线程池中其他具有相同优先级的线程提供机会。不能保证会立即使当前正在执行的线程处于可运行状态。当达到超时时间时,主线程和是同样可能的执行者候选。下一篇并发编程线程安全性深层原因

Thread

使用Java的同学对Thread应该不陌生了,线程的创建和启动等这里就不讲了,这篇主要讲几个容易被忽视的方法以及线程状态迁移。

wait/notify/notifyAll

首先我们要明白这三个方法是定义在Object类中,他们起到的作用就是允许线程就资源的锁定状态进行通信。这里所说的资源一般就是指的我们常说的共享对象了,也就是说针对共享对象的锁定状态可以通过wait/notify/notifyAll来进行通信。我们先看下如何使用的,并对相应原理进行展开。

wait

wait方法告诉调用线程放弃锁定并进入休眠状态,直到其他某个线程进入同一个监视器(monitor)并调用notify方法。wait方法在等待之前释放锁,并在wait方法返回之前重新获取锁。wait方法实际上和同步锁紧密集成,补充同步机制无法直接实现的功能。
需要注意到wait方法在jdk源码中是final并且是native的本地方法,我们无法去覆盖此方法。
调用wait一般的方式如下:

</>复制代码

  1. synchronized(lockObject) {
  2. while(!condition) {
  3. lockObject.wait();
  4. }
  5. // 这里进行相应处理;
  6. }

注意这里使用while进行条件判断而没有使用if进行条件判断,原因是这里有个很重要的点容易被忽视,下面来自官方的建议:

</>复制代码

  1. 应该在循环中检查等待条件,原因是处于等待状态的线程可能会收到错误的警报和伪唤醒,如果不在循环条件中等待,程序就会在没有满足结束条件的情况下退出。
notify

notify方法唤醒了同一个对象上调用wait的线程。这里要注意notify并没有放弃对资源的锁定,他告诉等待的线程可以唤醒,但是作用在notify上synchronized同步块完成之前,实际上是不会放弃锁。因此,如果通知线程在同步块内,调用notify方法后,需要在进行10s的其他操作,那么等待的线程将会再至少等待10s。
notify一般的使用方式如下:

</>复制代码

  1. synchronized(lockObject) {
  2. // 确定条件
  3. lockObject.notify();
  4. // 如果需要可以加任意代码
  5. }
notifyAll

notifyAll会唤醒在同一个对象上调用wait方法的所有线程。在大多数情况下优先级最高的线程将被执行,但是也是无法完全保证会是这样。其他的与notify相同。

使用例子

下面的代码示例实现了队列空和满时线程阻塞已经非空非满时的通知:

生产者:

</>复制代码

  1. class Producer implements Runnable {
  2. private final List taskQueue;
  3. private final int MAX_CAPACITY;
  4. public Producer(List sharedQueue, int size) {
  5. this.taskQueue = sharedQueue;
  6. this.MAX_CAPACITY = size;
  7. }
  8. @Override
  9. public void run() {
  10. int counter = 0;
  11. while (true) {
  12. try {
  13. produce(counter++);
  14. } catch (InterruptedException ex) {
  15. ex.printStackTrace();
  16. }
  17. }
  18. }
  19. private void produce(int i) throws InterruptedException {
  20. synchronized (taskQueue) {
  21. while (taskQueue.size() == MAX_CAPACITY) {
  22. System.out.println("队列已满,线程" + Thread.currentThread().getName() + "进入等待,队列长度:" + taskQueue.size());
  23. taskQueue.wait();
  24. }
  25. Thread.sleep(1000);
  26. taskQueue.add(i);
  27. System.out.println("生产:" + i);
  28. taskQueue.notifyAll();
  29. }
  30. }
  31. }

消费者:

</>复制代码

  1. class Consumer implements Runnable {
  2. private final List taskQueue;
  3. public Consumer(List sharedQueue) {
  4. this.taskQueue = sharedQueue;
  5. }
  6. @Override
  7. public void run() {
  8. while (true) {
  9. try {
  10. consume();
  11. } catch (InterruptedException ex) {
  12. ex.printStackTrace();
  13. }
  14. }
  15. }
  16. private void consume() throws InterruptedException {
  17. synchronized (taskQueue) {
  18. while (taskQueue.isEmpty()) {
  19. System.out.println("队列已空,线程" + Thread.currentThread().getName() + "进入等待,队列长度:" + taskQueue.size());
  20. taskQueue.wait();
  21. }
  22. Thread.sleep(1000);
  23. int i = (Integer) taskQueue.remove(0);
  24. System.out.println("消费:" + i);
  25. taskQueue.notifyAll();
  26. }
  27. }
  28. }

测试代码:

</>复制代码

  1. public class ProducerConsumerExampleWithWaitAndNotify {
  2. public static void main(String[] args) {
  3. List taskQueue = new ArrayList<>();
  4. int MAX_CAPACITY = 5;
  5. Thread tProducer = new Thread(new Producer(taskQueue, MAX_CAPACITY), "Producer");
  6. Thread tConsumer = new Thread(new Consumer(taskQueue), "Consumer");
  7. tProducer.start();
  8. tConsumer.start();
  9. }
  10. }

部分输出如下:

</>复制代码

  1. 生产:0
  2. 生产:1
  3. 生产:2
  4. 生产:3
  5. 生产:4
  6. 队列已满,线程Producer进入等待,队列长度:5
  7. 消费:0
  8. 消费:1
  9. 消费:2
  10. 消费:3
  11. 消费:4
  12. 队列已空,线程Consumer进入等待,队列长度:0
yield/join yield

从字面意思理解yield可以是谦让、放弃、屈服、投降的意思。一个要“谦让”的线程其实是在告诉虚拟机他愿意让其他线程安排到他的前面,这表明他没有说明重要的事情要做了。注意了这只是个提示,并不能保证能起到任何效果。
yield在Thread.java中定义如下:

</>复制代码

  1. /**
  2. * A hint to the scheduler that the current thread is willing to yield
  3. * its current use of a processor. The scheduler is free to ignore this
  4. * hint.
  5. * *

    Yield is a heuristic attempt to improve relative progression

  6. * between threads that would otherwise over-utilise a CPU. Its use
  7. * should be combined with detailed profiling and benchmarking to
  8. * ensure that it actually has the desired effect.
  9. * *

    It is rarely appropriate to use this method. It may be useful

  10. * for debugging or testing purposes, where it may help to reproduce
  11. * bugs due to race conditions. It may also be useful when designing
  12. * concurrency control constructs such as the ones in the
  13. * {@link java.util.concurrent.locks} package.
  14. */
  15. public static native void yield();

从这里面我们总结出一些重点(有关线程状态后面会讲到):

yield方法是一个静态的并且是native的方法。

yield告诉当前执行的线程为线程池中其他具有相同优先级的线程提供机会。

不能保证yield会立即使当前正在执行的线程处于可运行状态。

他只能使得线程从运行状态变成可运行状态,而无法做其他状态改变。

yield使用例子:

</>复制代码

  1. public class YieldExample {
  2. public static void main(String[] args) {
  3. Thread producer = new Producer();
  4. Thread consumer = new Consumer();
  5. producer.setPriority(Thread.MIN_PRIORITY); // 最低优先级
  6. consumer.setPriority(Thread.MAX_PRIORITY); // 最高优先级
  7. producer.start();
  8. consumer.start();
  9. }
  10. }
  11. class Producer extends Thread {
  12. public void run() {
  13. for (int i = 0; i < 5; i++) {
  14. System.out.println("生产者 : 生产 " + i);
  15. Thread.yield();
  16. }
  17. }
  18. }
  19. class Consumer extends Thread {
  20. public void run() {
  21. for (int i = 0; i < 5; i++) {
  22. System.out.println("消费者 : 消费 " + i);
  23. Thread.yield();
  24. }
  25. }
  26. }

当注释两个“Thread.yield();”时输出:

</>复制代码

  1. 消费者 : 消费 0
  2. 消费者 : 消费 1
  3. 消费者 : 消费 2
  4. 消费者 : 消费 3
  5. 消费者 : 消费 4
  6. 生产者 : 生产 0
  7. 生产者 : 生产 1
  8. 生产者 : 生产 2
  9. 生产者 : 生产 3
  10. 生产者 : 生产 4

当不注释两个“Thread.yield();”时输出:

</>复制代码

  1. 生产者 : 生产 0
  2. 消费者 : 消费 0
  3. 生产者 : 生产 1
  4. 消费者 : 消费 1
  5. 生产者 : 生产 2
  6. 消费者 : 消费 2
  7. 生产者 : 生产 3
  8. 消费者 : 消费 3
  9. 生产者 : 生产 4
  10. 消费者 : 消费 4
join

join方法用于将线程当前执行点连接到另一个线程的执行结束,这样这个线程就不会开始运行直到另一个线程结束。在Thread实例上调用join,则当前运行的线程将会阻塞,直到这个Thread实例完成执行。
简要摘抄Thread.java源码中join的定义:

</>复制代码

  1. // Waits for this thread to die.
  2. public final void join() throws InterruptedException

join还有可以传入时间参数的重载方法,这个可以时join的效果在特定时间后无效。当达到超时时间时,主线程和taskThread是同样可能的执行者候选。但是join和sleep一样,依赖于OS进行计时,不应该假定刚好等待指定的时间。
join和sleep一样也通过InterruptedException来响应中断。
join使用示例:

</>复制代码

  1. public class JoinExample {
  2. public static void main(String[] args) throws InterruptedException {
  3. Thread t = new Thread(new Runnable() {
  4. public void run() {
  5. System.out.println("第一个任务启动");
  6. System.out.println("睡眠2s");
  7. try {
  8. Thread.sleep(2000);
  9. } catch (InterruptedException e) {
  10. e.printStackTrace();
  11. }
  12. System.out.println("第一个任务完成");
  13. }
  14. });
  15. Thread t1 = new Thread(new Runnable() {
  16. public void run() {
  17. System.out.println("第二个任务完成");
  18. }
  19. });
  20. t.start();
  21. t.join();
  22. t1.start();
  23. }
  24. }

输出结果:

</>复制代码

  1. 第一个任务启动
  2. 睡眠2s
  3. 第一个任务完成
  4. 第二个任务完成
join原理分析

join在Thread.java中有三个重载方法:

</>复制代码

  1. public final void join() throws InterruptedException
  2. public final synchronized void join(long millis) throws InterruptedException
  3. public final synchronized void join(long millis, int nanos) throws InterruptedException

查看源码可以得知最终的实现核心部分都在join(long millis)中,我们来分析下这个方法源码:

</>复制代码

  1. public final synchronized void join(long millis)
  2. throws InterruptedException {
  3. long base = System.currentTimeMillis();
  4. long now = 0;
  5. if (millis < 0) {
  6. throw new IllegalArgumentException("timeout value is negative");
  7. }
  8. if (millis == 0) {
  9. while (isAlive()) {
  10. wait(0);
  11. }
  12. } else {
  13. while (isAlive()) {
  14. long delay = millis - now;
  15. if (delay <= 0) {
  16. break;
  17. }
  18. wait(delay);
  19. now = System.currentTimeMillis() - base;
  20. }
  21. }
  22. }

首先可以看到这个方法是使用synchronized修饰的同步方法,从这个方法的源码可以看出join的核心就是使用wait来实现的,而外部条件就是isAlive(),可以断定,在非isAlive()时会进行notify。

线程状态

在Thread.java的源代码中就体现出了六种状态:

</>复制代码

  1. /**
  2. * A thread state. A thread can be in one of the following states:
  3. *
    • *
    • {@link #NEW}
    • * A thread that has not yet started is in this state.
    • *
    • *
    • {@link #RUNNABLE}
    • * A thread executing in the Java virtual machine is in this state.
    • *
    • *
    • {@link #BLOCKED}
    • * A thread that is blocked waiting for a monitor lock
    • * is in this state.
    • *
    • *
    • {@link #WAITING}
    • * A thread that is waiting indefinitely for another thread to
    • * perform a particular action is in this state.
    • *
    • *
    • {@link #TIMED_WAITING}
    • * A thread that is waiting for another thread to perform an action
    • * for up to a specified waiting time is in this state.
    • *
    • *
    • {@link #TERMINATED}
    • * A thread that has exited is in this state.
    • *
    • *
  4. *
  5. *

  6. * A thread can be in only one state at a given point in time.
  7. * These states are virtual machine states which do not reflect
  8. * any operating system thread states.
  9. *
  10. * @since 1.5
  11. * @see #getState
  12. */
  13. public enum State {
  14. /**
  15. * Thread state for a thread which has not yet started.
  16. */
  17. NEW,
  18. /**
  19. * Thread state for a runnable thread. A thread in the runnable
  20. * state is executing in the Java virtual machine but it may
  21. * be waiting for other resources from the operating system
  22. * such as processor.
  23. */
  24. RUNNABLE,
  25. /**
  26. * Thread state for a thread blocked waiting for a monitor lock.
  27. * A thread in the blocked state is waiting for a monitor lock
  28. * to enter a synchronized block/method or
  29. * reenter a synchronized block/method after calling
  30. * {@link Object#wait() Object.wait}.
  31. */
  32. BLOCKED,
  33. /**
  34. * Thread state for a waiting thread.
  35. * A thread is in the waiting state due to calling one of the
  36. * following methods:
  37. *

    • *
    • {@link Object#wait() Object.wait} with no timeout
    • *
    • {@link #join() Thread.join} with no timeout
    • *
    • {@link LockSupport#park() LockSupport.park}
    • *
  38. *
  39. *

    A thread in the waiting state is waiting for another thread to

  40. * perform a particular action.
  41. *
  42. * For example, a thread that has called Object.wait()
  43. * on an object is waiting for another thread to call
  44. * Object.notify() or Object.notifyAll() on
  45. * that object. A thread that has called Thread.join()
  46. * is waiting for a specified thread to terminate.
  47. */
  48. WAITING,
  49. /**
  50. * Thread state for a waiting thread with a specified waiting time.
  51. * A thread is in the timed waiting state due to calling one of
  52. * the following methods with a specified positive waiting time:
  53. *

    • *
    • {@link #sleep Thread.sleep}
    • *
    • {@link Object#wait(long) Object.wait} with timeout
    • *
    • {@link #join(long) Thread.join} with timeout
    • *
    • {@link LockSupport#parkNanos LockSupport.parkNanos}
    • *
    • {@link LockSupport#parkUntil LockSupport.parkUntil}
    • *
  54. */
  55. TIMED_WAITING,
  56. /**
  57. * Thread state for a terminated thread.
  58. * The thread has completed execution.
  59. */
  60. TERMINATED;
  61. }

一般我们用如下图来表示状态迁移,注意相关方法。(注意:其中RUNNING和READY是无法直接获取的状态。)

下一篇:Java并发编程——线程安全性深层原因

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/72737.html

相关文章

  • Java并发编程——线程安全性深层原因

    摘要:线程安全性深层原因这里我们将会从计算机硬件和编辑器等方面来详细了解线程安全产生的深层原因。类似这种不影响单线程语义的乱序执行我们称为指令重排。通过线程安全性深层原因我们能更好的理解这三大性质的根本性原因。上一篇并发编程线程基础查漏补缺 线程安全性深层原因 这里我们将会从计算机硬件和编辑器等方面来详细了解线程安全产生的深层原因。 缓存一致性问题 CPU内存架构 随着CPU的发展,而因为C...

    Faremax 评论0 收藏0
  • 作为我的的第一门语言,学习Java时是什么感受?

    摘要:作为技术书籍或者视频,讲解一门语言的时候都是从最底层开始讲解,底层的基础有哪些呢首先是整个,让我们对这门语言先混个脸熟,知道程序的基本结构,顺带着还会说一下注释是什么样子。 2018年新年刚过,就迷茫了,Java学不下去了,不知道从哪里学了。 那么多细节的东西,我根本记不住,看完就忘。 刚开始学习的时候热情万丈,持续不了几天就慢慢退去。 作为技术书籍或者视频,讲解一门语言的时候都是...

    isaced 评论0 收藏0
  • 【面试篇】JS基础知识查漏补缺

    摘要:因为在页面加载完成后,引擎维护着两个队列,一个是按页面顺序加载的执行队列,还有一个空闲队列,使用定时函数就是将回调函数加入到空闲队列中,故和其他定时器是并发执行的。 1.window.onload和$(document).ready()的区别: ①执行时间:window.onload会在所有元素,包括图片,引用文件加载完成之后执行,而$(document).ready()则会在HTML...

    myeveryheart 评论0 收藏0
  • 【推荐】最新200篇:技术文章整理

    摘要:作为面试官,我是如何甄别应聘者的包装程度语言和等其他语言的对比分析和主从复制的原理详解和持久化的原理是什么面试中经常被问到的持久化与恢复实现故障恢复自动化详解哨兵技术查漏补缺最易错过的技术要点大扫盲意外宕机不难解决,但你真的懂数据恢复吗每秒 作为面试官,我是如何甄别应聘者的包装程度Go语言和Java、python等其他语言的对比分析 Redis和MySQL Redis:主从复制的原理详...

    BicycleWarrior 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<