9.线程通信wait、notify

线程之间通信
1.线程是操作系统的独立的个体,但这些个体如果不经过特殊处理就不能成为一个整体。
2.使用wait、notify,方法实现线程通信(2个方法都是需要object方法)
3.wait(释放锁)、notify(不会释放锁)必须配合synchronized关键字使用。
  1. package demo2;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. /**
  5. * Created by liudan on 2017/7/4.
  6. */
  7. public class MyThread2_2 {
  8. private volatile static List<String> lsit = new ArrayList<String>();
  9. public void add() {
  10. lsit.add("add......");
  11. }
  12. public int size() {
  13. return lsit.size();
  14. }
  15. public static void main(String[] args) {
  16. final MyThread2_1 myThread2_1 = new MyThread2_1();
  17. final Object o = new Object();
  18. Thread t1 = new Thread(new Runnable() {
  19. @Override
  20. public void run() {
  21. synchronized (o) {
  22. try {
  23. for (int i = 0; i < 10; i++) {
  24. myThread2_1.add();
  25. System.err.println("当前线程:" + Thread.currentThread().getName() + "添加了一个元素");
  26. Thread.sleep(500);
  27. if (myThread2_1.size() == 5) {
  28. System.err.println("发起通知");
  29. o.notify();
  30. }
  31. }
  32. } catch (InterruptedException e) {
  33. e.printStackTrace();
  34. }
  35. }
  36. }
  37. }, "t1");
  38. Thread t2 = new Thread(new Runnable() {
  39. @Override
  40. public void run() {
  41. synchronized (o) {
  42. if (myThread2_1.size()!= 5) {
  43. System.err.println("t2 进入");
  44. try {
  45. o.wait();
  46. } catch (InterruptedException e) {
  47. e.printStackTrace();
  48. }
  49. }
  50. System.err.println("当前线程:" + Thread.currentThread().getName() + "收到通知...");
  51. }
  52. }
  53. }, "t2");
  54. t2.start();
  55. t1.start();
  56. }
  57. }



posted @ 2017-08-07 23:13  逍遥叹!!  阅读(189)  评论(0编辑  收藏  举报