线程生命周期状态

image.png
image.png

线程池中的线程为什么可以复用?

线程池 其实就是管理线程的容器。
一句话解释:
就是run方法没有执行完,而是在run方法里面设置一个循环。线程没有被使用的时候处于阻塞暂停状态,需要使用的时候阻塞打开,执行任务,任务完成之后,再循环回来,再次阻塞暂停。此时仍在循环当中。所以run方法一直也没有结束,因此可以重复使用多次。

Threadlocal使用案例

image.png

image.png

2个线程交替打印奇偶数

  1. package test2005;
  2. public class test {
  3. private static volatile Integer counter = 0;
  4. private static Object monitor = new Object();
  5. public static void main(String[] args) {
  6. new Thread(new Runnable() {
  7. // 奇数线程
  8. @Override
  9. public void run() {
  10. while (true){
  11. synchronized (monitor){
  12. if (counter % 2 != 0){
  13. continue;
  14. }
  15. int i = ++counter;
  16. if (i > 100){
  17. return;
  18. }
  19. System.out.println("奇数线程:" + i);
  20. try {
  21. monitor.notify();
  22. monitor.wait();
  23. } catch (InterruptedException e) {
  24. e.printStackTrace();
  25. }
  26. }
  27. }
  28. }
  29. }).start();
  30. new Thread(new Runnable() {
  31. @Override
  32. public void run() {
  33. while (true){
  34. synchronized (monitor){
  35. if (counter % 2 == 0){
  36. continue;
  37. }
  38. int i = ++counter;
  39. if (i > 100){
  40. return;
  41. }
  42. System.out.println("偶数线程:" + i);
  43. try {
  44. monitor.notify();
  45. monitor.wait();
  46. } catch (InterruptedException e) {
  47. e.printStackTrace();
  48. }
  49. }
  50. }
  51. }
  52. }).start();
  53. }
  54. }

1.wait
wait(),当前线程进入 无限等待状态,必须被唤醒才能继续执行,调用后会释放锁对象
wait(long timeout),wait(long timeout,int nanos),当前线程进入等待状态,可以被提前唤醒,但在指定时间后会自动唤醒
2.notify
notify(), 随机唤醒一个在锁对象上调用wait的线程
notifyAll(),唤醒 全部在锁对象上调用wait的线程
————————————————
版权声明:本文为CSDN博主「omelete」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_31075041/article/details/106931481