Java并發(fā)編程基礎(chǔ)知識(shí)片段
片斷一
在main中啟動(dòng)兩個(gè)線程,例如:
Thread a=new Thread(){
public void run(){
System.out.println("Call A");
try{
Thread.sleep(1000);
}
catch(Exception e){
e.printStackTrace();
}
}
};
Thread b=new Thread(){
public void run(){
try{
Thread.sleep(500);
}
catch(Exception e){
e.printStackTrace();
}
System.out.println("Call B");
}
};
a.start();
b.start();
System.out.println("execute here");
在這樣的方式下,執(zhí)行時(shí)會(huì)出現(xiàn)什么樣的效果;
怎么樣才能保證字符串的打印順序是:"Call B"-->"Call A"-->"execute here"呢?(提示:join、wait/notify、Semphore、Lock等)
在做到了上面打印順序控制后,怎么樣才能做到如果線程b執(zhí)行了100毫秒還沒(méi)執(zhí)行完的話(huà)則直接繼續(xù)線程a的執(zhí)行呢?(提示:ExecutorServices、Future)
片段二
也是個(gè)控制順序的問(wèn)題,假設(shè)有如下一段代碼:
for(int i=0;i<10;i++){
Thread thread=new Thread(){
public void run(){
...
}
};
thread.setName("Thread-"+i);
thread.start();
}
System.out.println("All Executed");
需要做到所有線程同時(shí)運(yùn)行,而不是按照f(shuō)or的順序一個(gè)一個(gè)啟動(dòng),并且要求All Executed需要在所有線程都執(zhí)行完畢后才打印,有什么辦法做到呢?(提示:CountDownLatch等)
片段三
Map<String,Object> datas=new ConcurrentHashMap<String,Object>();
public Object get(String keyName){
Object data=null;
if(!datas.containsKey(keyName)){
data=createData(keyName);
datas.put(keyName,data);
}
else{
data=datas.get(keyName;)
}
return data;
}
上面這段代碼在并發(fā)時(shí)會(huì)出什么問(wèn)題呢,為什么?
如果有問(wèn)題的話(huà),應(yīng)該怎么去解決呢?(提示:Synchronized、Lock、FutureTask等)
片段四
ThreadPoolExecutor executor=new ThreadPoolExecutor(10,100,60L,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(20),new ThreadPoolExecutor.AbortPolicy());
一個(gè)這樣的線程池,當(dāng)并發(fā)請(qǐng)求數(shù)為15時(shí)會(huì)是怎么個(gè)狀況?(池的使用狀況,例如活動(dòng)線程數(shù)、隊(duì)列中的數(shù)等)
當(dāng)并發(fā)請(qǐng)求數(shù)為100的時(shí)候是什么狀況?
當(dāng)并發(fā)請(qǐng)求數(shù)為200的時(shí)候是什么狀況?
當(dāng)30秒內(nèi)不再有請(qǐng)求時(shí)會(huì)怎么樣?
當(dāng)2分鐘內(nèi)沒(méi)有請(qǐng)求時(shí)會(huì)怎么樣?
如果換成以下方式初始化池又會(huì)怎么樣呢:
ThreadPoolExecutor executor=new ThreadPoolExecutor(10,150,20L,TimeUnit.SECONDS,new SynchronousQueue<Runnable>(),new ThreadPoolExecutor.AbortPolicy());
片段五
怎么查看jvm中線程的執(zhí)行狀況,線程的狀態(tài)有哪幾種,分別表示什么含義?
ThreadFactory有什么用?
如果要捕捉線程中拋出的異常,可以怎么做呢?
如果TimerTask拋出運(yùn)行時(shí)異常會(huì)不會(huì)影響到同一個(gè)Timer中其他的TimerTask的執(zhí)行呢,SchedularThreadPoolExecutor和Timer有什么不同?
片段六
常見(jiàn)的一個(gè)例子:
private int count;
public synchronized int getNext(){
return count++;
}
在JDK5有什么別的方法來(lái)進(jìn)行實(shí)現(xiàn)嗎?
像JDK5中的AtomicInteger的incrementAndGet是怎么實(shí)現(xiàn)的呢?
如果這個(gè)count要按線程來(lái)獨(dú)立管理,即每個(gè)線程有自己的一個(gè)count,要怎么做呢?
posted on 2008-06-20 01:29 BlueDavy 閱讀(7930) 評(píng)論(4) 編輯 收藏 所屬分類(lèi): Java