线程通信的例子:使用两个线程打印1-100。线程1,线程2,交替打印

  1. /**
  2. * 线程通信的例子:使用两个线程打印1-100。线程1,线程2,交替打印
  3. *
  4. * 涉及到的三个方法:
  5. * wait():一旦执行此方法,当前线程就进入阻塞状态,并释放同步监视器。
  6. * notify():一旦执行此方法,就会唤醒被wait的一个线程。如果有多个线程被wait,就唤醒优先级高的那个。
  7. * notifyAll():旦执行此方法,就会唤醒所有被wait的线程。
  8. *
  9. * 说明:
  10. * 1.wait() notify() notifyAll() 这三个方法必须使用在同步代码块或同步方法中。
  11. * 2.wait() notify() notifyAll() 这三个方法必须是同步代码块或同步方法中的同步监视器
  12. * 否则,会出现IllegalMonitorStateException异常
  13. * 3.wait() notify() notifyAll() 这三个方法是定义在java.Lang.Object类中。
  14. *
  15. * 面试题:sleep() 和 wait()的异同?
  16. * 1.相同点:一旦执行方法,都可以使得当前的线程进入阻塞状态。
  17. * 2.不同点:1)两个方法声明的位置不同:Thread类中声明sleep(),Object类中声明wait()
  18. * 2)调用的要求不同:sleep()可以再任何需要的场景下调用。wait()必须使用在同步代码块或同步方法中。
  19. * 3)关于是否释放同步监视器:如果两个方法都使用在同步代码块或同步方法中,sleep()不会释放锁,wait()会释放锁。
  20. *
  21. *
  22. * @author JiaMing_Xu
  23. * @create 2024-09-10-15:54
  24. */
  25. class Number implements Runnable{
  26. private int number = 1;
  27. @Override
  28. public void run() {
  29. while (true){
  30. synchronized (this) {
  31. this.notifyAll();
  32. if (number <= 100){
  33. try {
  34. Thread.sleep(10);
  35. } catch (InterruptedException e) {
  36. e.printStackTrace();
  37. }
  38. System.out.println(Thread.currentThread().getName() + ":" + number);
  39. number++;
  40. try {
  41. //使得调用如下wait()方法的线程进入阻塞状态
  42. wait();
  43. }catch (InterruptedException e){
  44. e.printStackTrace();
  45. }
  46. }else{
  47. break;
  48. }
  49. }
  50. }
  51. }
  52. }
  53. public class CommunicationTest {
  54. public static void main(String[] args) {
  55. Number number = new Number();
  56. Thread t1 = new Thread(number);
  57. Thread t2 = new Thread(number);
  58. t1.setName("线程1");
  59. t2.setName("线程2");
  60. t1.start();
  61. t2.start();
  62. }
  63. }
赠人玫瑰,手留余香
基础入门--抓包
文件包含漏洞