public static void main(String[] args){
Map<Integer, Object> tables = new Hashtable<Integer, Object>();
Thread add = new Thread(new ThreadAdd(tables));
Thread del = new Thread(new ThreadDel(tables));
Thread count = new Thread(new ThreadCount(tables));
//啟動線程
add.start();
del.start();
count.start();
}
/**
*添加對象線程
*/
private static class ThreadAdd implements Runnable{
private Map<Integer, Object> table;
public ThreadAdd(Map<Integer, Object> tables){
this.table=tables;
}
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<10;i++){
table.put(i, new Object());
System.out.println("添加對象,序號為:"+i);
}
}
}
/**
*刪除對象線程
*/
private static class ThreadDel implements Runnable{
private Map<Integer, Object> table;
public ThreadDel(Map<Integer, Object> table){
this.table=table;
}
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<10;i++){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
table.remove(i);
System.out.println("移除對象,序號為:"+i);
}
}
}
/**
*統計線程
*/
private static class ThreadCount implements Runnable{
private Map<Integer, Object> table;
public ThreadCount(Map<Integer, Object> table){
this.table=table;
}
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<10;i++){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("當前隊列還剩"+table.size()+"個對象");
}
}
}
}
這是我的寫的demo,不知道符合不符合妳的意思,大家***同交流***同進步。