线程通信方式:休眠唤醒方式

女爷i 2024-04-19 13:24 144阅读 0赞
  1. /*线程之间的通信方式:方式一:使用notify+wait+object实现线程之间的通信*/
  2. /*实例:奇数线程打印10以内的奇数,偶数线程打印10以内的偶数*/
  3. public class ThreadCommunication {
  4. private int i = 0;
  5. /*相当于synchronized 的钥匙*/
  6. private Object object = new Object();
  7. /*奇数*/
  8. public void odd() {
  9. synchronized (object){
  10. while (i < 10) {
  11. if (i % 2 == 1) {
  12. System.out.println("奇数:" + i);
  13. i++;
  14. /*唤醒该线程*/
  15. object.notify();
  16. } else {
  17. try {
  18. /*该线程等待*/
  19. object.wait();
  20. } catch (InterruptedException e) {
  21. e.printStackTrace();
  22. }
  23. }
  24. }
  25. }
  26. }
  27. /*偶数*/
  28. public void even() {
  29. synchronized (object){
  30. while (i < 10) {
  31. if (i % 2 == 0) {
  32. System.out.println("偶数:" + i);
  33. i++;
  34. /*唤醒该线程*/
  35. object.notify();
  36. } else {
  37. try {
  38. /*该线程等待*/
  39. object.wait();
  40. } catch (InterruptedException e) {
  41. e.printStackTrace();
  42. }
  43. }
  44. }
  45. }
  46. }
  47. public static void main(String[] args) {
  48. ThreadCommunication threadCommunication = new ThreadCommunication();
  49. Thread thread1 = new Thread("thread1"){
  50. @Override
  51. public void run() {
  52. threadCommunication.odd();
  53. }
  54. };
  55. Thread thread2 = new Thread("thread2"){
  56. @Override
  57. public void run() {
  58. threadCommunication.even();
  59. }
  60. };
  61. thread1.start();
  62. thread2.start();
  63. }
  64. }
  65. /*
  66. * 若不用synchronized (object){} 则会抛出如下异常:java.lang.IllegalMonitorStateException
  67. * 原因:
  68. * 线程操作的wait()、notify()、notifyAll()方法只能在同步控制方法或同步控制块内调用。
  69. * 如果在非同步控制方法或控制块里调用,程序能通过编译,
  70. * 但运行的时候,将得到 IllegalMonitorStateException 异常
  71. * */

发表评论

表情:
评论列表 (有 0 条评论,144人围观)

还没有评论,来说两句吧...

相关阅读