处理线程协作时,在同步方法中,必须作进入检查,如果不满足进入条件,须放弃锁,进入等待
完成业务处理后,要做清场处理,同时完成唤醒其他等待的线程的操作
1. import java.util.ArrayList;
2. import java.util.List;
3. /** 定义一个盘子类,可以放鸡蛋和取鸡蛋 */
4. public class Plate {
5. /** 装鸡蛋的盘子 */
6. List<Object> eggs = new ArrayList<Object>();
7. /** 取鸡蛋 */
8. public synchronized Object getEgg() {
9. while (eggs.size() == 0) {
10. try {
11. wait();
12. } catch (InterruptedException e) {
13. e.printStackTrace();
14. }
15. }
16. Object egg = eggs.get(0);
17. eggs.clear();// 清空盘子
18. notify();// 唤醒阻塞队列的某线程到就绪队列
19. System.out.println("拿到鸡蛋");
20. return egg;
21. }
22. /** 放鸡蛋 */
23. public synchronized void putEgg(Object egg) {
24. while (eggs.size() > 0) {
25. try {
26. wait();
27. } catch (InterruptedException e) {
28. e.printStackTrace();
29. }
30. }
31. eggs.add(egg);// 往盘子里放鸡蛋
32. notify();// 唤醒阻塞队列的某线程到就绪队列
33. System.out.println("放入鸡蛋");
34. }
35. static class AddThread implements Runnable {
36. private Plate plate;
37. private Object egg = new Object();
38. public AddThread(Plate plate) {
39. this.plate = plate;
40. }
41. public void run() {
42. plate.putEgg(egg);
43. }
44. }
45. static class GetThread implements Runnable {
46. private Plate plate;
47. public GetThread(Plate plate) {
48. this.plate = plate;
49. }
50. public void run() {
51. plate.getEgg();
52. }
53. }
54. public static void main(String args[]) {
55. Plate plate = new Plate();
56. for(int i = 0; i < 10; i++) {
57. new Thread(new AddThread(plate)).start();
58. new Thread(new GetThread(plate)).start();
59. }
60. }
61. }
1. import java.util.ArrayList;
2. import java.util.List;
3. /** 定义一个盘子类,可以放鸡蛋和取鸡蛋 */
4. public class Plate {
5. /** 装鸡蛋的盘子 */
6. List<Object> eggs = new ArrayList<Object>();
7. /** 取鸡蛋 */
8. public synchronized Object getEgg() {
9. while (eggs.size() == 0) {
10. try {
11. wait();
12. } catch (InterruptedException e) {
13. e.printStackTrace();
14. }
15. }
16. Object egg = eggs.get(0);
17. eggs.clear();// 清空盘子
18. notify();// 唤醒阻塞队列的某线程到就绪队列
19. System.out.println("拿到鸡蛋");
20. return egg;
21. }
22. /** 放鸡蛋 */
23. public synchronized void putEgg(Object egg) {
24. while (eggs.size() > 0) {
25. try {
26. wait();
27. } catch (InterruptedException e) {
28. e.printStackTrace();
29. }
30. }
31. eggs.add(egg);// 往盘子里放鸡蛋
32. notify();// 唤醒阻塞队列的某线程到就绪队列
33. System.out.println("放入鸡蛋");
34. }
35. static class AddThread implements Runnable {
36. private Plate plate;
37. private Object egg = new Object();
38. public AddThread(Plate plate) {
39. this.plate = plate;
40. }
41. public void run() {
42. plate.putEgg(egg);
43. }
44. }
45. static class GetThread implements Runnable {
46. private Plate plate;
47. public GetThread(Plate plate) {
48. this.plate = plate;
49. }
50. public void run() {
51. plate.getEgg();
52. }
53. }
54. public static void main(String args[]) {
55. Plate plate = new Plate();
56. for(int i = 0; i < 10; i++) {
57. new Thread(new AddThread(plate)).start();
58. new Thread(new GetThread(plate)).start();
59. }
60. }
61. }