Posted on 2007-11-09 01:31
dybjsun 阅读(204)
评论(0) 编辑 收藏 所属分类:
多线程主题
当多线程启动时,怎么才能控制他们有秩序地执行。本例模拟一个容器,当容器里有东西时,通知各个线程来取得这些东西,如果没有取到东西,则进入等待状态。(特别注意在通知各个线程notifyAll和等待wait这些方法一定要写在同步块中)
1 package com.noahsi.fulltextsearch.index.basic;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6 import com.noahsi.fulltextsearch.index.model.LinkModel;
7 import com.noahsi.fulltextsearch.util.Debug;
8
9 public class Container {
10
11 private List container = null;
12
13 public Container() {
14 container = new ArrayList();
15 }
16
17 public Container(LinkModel model) {
18 container = new ArrayList();
19 container.add(model);
20 }
21
22 public Container(List list) {
23 container = new ArrayList();
24 container.addAll(list);
25 }
26
27 public synchronized void listener() {
28 if (container.size() > 0) {
29 this.notifyAll();
30 }
31 }
32
33 public synchronized LinkModel getLinkModel() {
34 if (container.size() == 0) {
35 try {
36 this.wait();
37 } catch (InterruptedException ie) {
38 }
39 return null;
40 }
41 return (LinkModel) container.remove(0);
42 }
43
44 public synchronized void putLinksModel(List links) {
45 LinkModel temp = null;
46 for (int i = 0; i < links.size(); i++) {
47 temp = (LinkModel) links.get(i);
48 if (!container.contains(temp)) {
49 container.add(temp);
50 }
51 }
52 this.notifyAll();
53 }
54
55 public synchronized void putLinkModel(LinkModel model) {
56 if (model != null) {
57 container.add(model);
58 }
59 this.notifyAll();
60 }
61
62 public synchronized void active() {
63 this.notifyAll();
64 }
65
66 public int getSize() {
67 return container.size();
68 }
69 }