解决方案 »
- 集合类问题
- 求助,新手问题.
- 如何使我的SQL执行时使用我建的索引?顶者有分,有答案马上结贴!!
- 关于遍历文件夹和生成新文件?
- 100分求教 CVSNT 和WINCVS配置问题
- JBuilder Borland Make 居然不能编译import不属于任何包的class,解决全部分
- j2ee, ejbいe穨 ぃ笵╯澈林穨Τぐ或闽玒
- 哎!文件拷贝之后,里面的中文就成了乱码了.怎么才能让中文显示正常???
- 我下载一个Jbuilder7的ISO的盘638M的怎么不能安装呀
- How to add a Calendar & clock to web and got date&time ?
- 求助: Java POI如何输出带函数公式的单元格
- 本人Java菜鸟问几个关于图形化界面聊天软件的问题,望高手指点迷津!
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;public class Demo5 {
private static List<People> peoples = new ArrayList<People>(); public static void main(String[] args) {
for (int i = 0; i < 18; i++) {
peoples.add(new People("#" + i + "people"));
} Demo5 demo = new Demo5();
ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(demo.new ViewPeople());
exec.execute(demo.new ViewPeople());
exec.shutdown();
} class ViewPeople implements Runnable { public void run() {
try {
while (!Thread.interrupted()) {
synchronized (peoples) {
if (peoples.size() > 0) {
People people = peoples.get(0);
System.out.println(people);
peoples.remove(people);
} else {
break;
}
}
}
} catch (Exception e) {
}
} }
}class People {
private static int count;
private final int id = count++;
private String name; public People(String name) {
this.name = name;
} public int getId() {
return id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} @Override
public String toString() {
return id + ": " + name;
}}
2、不要用arraylist,改用线程安全的队列。
这样每次只有一个线程在访问List,我需要2个线程同时可以访问List
这样每次只有一个线程在访问List,我需要2个线程同时可以访问List
这样每次只有一个线程在访问List,我需要2个线程同时可以访问List
一个list对象只有一个对象锁, 怎么同时访问, 除非不同步控制
那就用lock。
A使用P时尝试获取lock,成功继续操作。
B尝试获取lock,失败则P正在被使用。