首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

空中网的一个用线程操作集合遇到的有关问题

2012-10-09 
空中网的一个用线程操作集合遇到的问题package com.test/** * 当每个线程中指定的KEY相同时, * 这些相同K

空中网的一个用线程操作集合遇到的问题

package com.test;/** * 当每个线程中指定的KEY相同时, * 这些相同KEY的线程应每隔一秒依次输出时间值(互斥), * 如果KEY不同,则并行执行(相互之间不互斥) */public class Test extends Thread{private TestDo testDo;private String key = "1";private String value;public Test(String key,String key2,String value){testDo = TestDo.getInstance();this.key = new String(key+key2);this.value = value;}public static void main(String[] args){Test a1 = new Test("1","","1");Test a2 = new Test("1","","2");Test a3 = new Test("1","","3");Test a4 = new Test("1","","4");Test b1 = new Test("2","","1");Test c1 = new Test("3","","1");Test d1 = new Test("4","","1");System.out.println("begin:"+(System.currentTimeMillis()/1000));a1.start();a2.start();a3.start();a4.start();b1.start();c1.start();d1.start();}@Overridepublic void run(){try{testDo.doSome(key, value);}catch(Exception e){e.printStackTrace();}}}

package com.test;import java.util.Iterator;import java.util.Random;import java.util.Set;import java.util.concurrent.CopyOnWriteArraySet;public class TestDo{private Set set = new CopyOnWriteArraySet();private TestDo(){};private static TestDo testDo = new TestDo();public static TestDo getInstance(){return testDo;}public void doSome(String key, String value) throws Exception{Object o = null;if (!set.contains(key)){set.add(key);o = key;}else{for(Iterator it = set.iterator();it.hasNext();){Object oo = it.next();Thread.sleep(new Random().nextInt(100));if(key.equals(oo)){o = oo;break;}}}synchronized(o){try{System.out.println(key + ":" + value + ":"+ (System.currentTimeMillis()/1000));}catch(Exception e){e.printStackTrace();}Thread.sleep(1000);}}}

热点排行