实验06 线程应用及线程并发库.docx
- 文档编号:27839499
- 上传时间:2023-07-05
- 格式:DOCX
- 页数:18
- 大小:374.86KB
实验06 线程应用及线程并发库.docx
《实验06 线程应用及线程并发库.docx》由会员分享,可在线阅读,更多相关《实验06 线程应用及线程并发库.docx(18页珍藏版)》请在冰豆网上搜索。
实验06线程应用及线程并发库
实验六线程应用及线程并发库
1.实验目的
(1)掌握Thread类、Runnalbe接口、Timer类、ThreadLocal、同步代码块、同步方法等的用法;
(2)掌握Semaphore、ReadWriteLock与Condition、Exchanger、BlockingQueue、CyclicBarrier、CountdownLatch等的用法;
(3)掌握线程池相关接口及类的用法。
2.实验内容
实验题1编写一程序,实现如下功能:
子线程循环10次,接着主线程循环100次,接着又回到子线程循环10次,主线程循环100次,如此循环50次。
package.jp.data;
publicclassFather_runimplementsRunnable{
privateFatherSonFunctionfsf=null;
publicFather_run(FatherSonFunctionfsf){
super();
this.fsf=fsf;
}
@Override
publicvoidrun(){
this.fsf.father();
}
}
package.jp.data;
publicclassSon_runimplementsRunnable{
privateFatherSonFunctionfsf=null;
publicSon_run(FatherSonFunctionfsf){
super();
this.fsf=fsf;
}
@Override
publicvoidrun(){
this.fsf.son();
}
}
package.jp.data;
publicclassFatherSonFunction{
privatebooleanflag=true;
publicsynchronizedvoidfather(){
while(flag){
try{
wait();
}catch(InterruptedExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
for(inti=1;i<=100;i++){
System.out.println("father:
"+i);
}
flag=false;
notify();
}
publicsynchronizedvoidson(){
while(!
flag){
try{
wait();
}catch(InterruptedExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
for(inti=1;i<=50;i++){
System.out.println("son:
"+i);
}
flag=false;
notify();
}
}
package.jp;
import.jp.data.FatherSonFunction;
import.jp.data.Father_run;
import.jp.data.Son_run;
publicclassFather_Son_Text{
/**
*@paramargs
*/
publicstaticvoidmain(String[]args){
FatherSonFunctionsrf=newFatherSonFunction();
Son_runsr=newSon_run(srf);
Father_runfr=newFather_run(srf);
for(inti=0;i<50;i++){
newThread(sr).start();
newThread(fr).start();
}
}
}
实验题2设计4个线程,其中2个线程每次对count增加1,另外两个线程每次对count减1。
package.jp.data;
publicclassCount{
publicstaticintcount=0;
}
package.jp.data;
publicclassCountAddextendsCountimplementsRunnable{
@Override
publicvoidrun(){
print();
}
privatesynchronizedvoidprint(){
super.count++;
System.out.println("Count:
"+count);
}
}
package.jp.data;
publicclassCountSubextendsCountimplementsRunnable{
@Override
publicvoidrun(){
print();
}
privatesynchronizedvoidprint(){
super.count--;
System.out.println("Count:
"+count);
}
}
packagejp;
import.jp.data.CountAdd;
import.jp.data.CountSub;
publicclassCount_Text{
/**
*@paramargs
*/
publicstaticvoidmain(String[]args){
CountAddca1=newCountAdd();
CountAddca2=newCountAdd();
CountSubcs1=newCountSub();
CountSubcs2=newCountSub();
newThread(ca1).start();
newThread(ca2).start();
//newThread(cs1).start();
//newThread(cs2).start();
}
}
实验题3CyclicBarrier是一个同步辅助类,它允许一组线程互相等待,直到到达某个公共屏障点。
在涉及一组固定大小的线程的程序中,这些线程必须不时地互相等待,此时CyclicBarrier很有用。
因为该barrier在释放等待线程后可以重用,所以称它为循环的barrier。
题目要求:
(1)要在公司大厅集合、然后参观陈云故居;
(2)参观完后集合、准备去淀水湖参观(有3辆车、对应3个线程);
说明:
必须等大家都到齐了才能去下个地方、比如说在公司集合、3辆车子都到了才能出发等。
要求:
用java线程并发库的CyclicBarrier类模拟上述参观过程。
packagecn.edu.cyclicBarrier.jp;
importjava.util.concurrent.BrokenBarrierException;
importjava.util.concurrent.CyclicBarrier;
publicclassCyclicBarrierTest2{
publicstaticvoidmain(String[]args){
finalCyclicBarriercb=newCyclicBarrier(3);
//finalSemaphoresemaphore=newSemaphore
(1);
for(inti=1;i<=3;i++){
newThread(newRunnable(){
@Override
publicvoidrun(){
try{
//semaphore.acquire();
System.out.println(Thread.currentThread().getName()
+"公司大厅集合");
System.out.println(Thread.currentThread().getName()
+"公司大厅等待....");
//semaphore.release();
cb.await();
Thread.sleep(2000);
//semaphore.acquire();
System.out.println(Thread.currentThread().getName()
+"陈云故居集合");
System.out.println(Thread.currentThread().getName()
+"陈云故居等待....");
//semaphore.release();
cb.await();
Thread.sleep(2000);
//semaphore.acquire();
System.out.println(Thread.currentThread().getName()
+"淀水湖集合");
System.out.println(Thread.currentThread().getName()
+"淀水湖等待....准备回家了");
//semaphore.release();
cb.await();
Thread.sleep(2000);
}catch(InterruptedExceptione){
e.printStackTrace();
}catch(BrokenBarrierExceptione){
e.printStackTrace();
}
}
}).start();
}
}
}
实验题4某图书馆邀请一著名作家签名售书,大家去买书,具体情况如下:
(1)买书的读者很多必须排队,作家签好名的书不多(但是他还会看书的销售的情况,一般满了10本(假设)就不会再签了);
(2)有的书还没有签名,这样排在前面的同学就可以买到书、排在后面的就必须等有了签过名的书才能买;
(3)已经签好名的书可以放在ArrayBlockingQueue中,签好名的书不断的向这个队列里放,而买书的读者不断的从里面取书,如没有签名的书,就必须等,书有10本了,作家就停下来休息。
买书的每个读者都可以看作一个线程、作家签名也可以看作是一个线程;
(4)排在前面的读者先买。
要求:
编写程序,模拟上述过程。
packagecn.edu.arrayblockingqueue.jp;
importjava.util.concurrent.ArrayBlockingQueue;
importjava.util.concurrent.Semaphore;
publicclassArrayBlockingQueueTest{
publicstaticvoidmain(String[]args){
finalArrayBlockingQueue
10,true);//注意此时设置了true、可与下面的进行比较
//finalArrayBlockingQueue
//10);
//finalSemaphoresemaphore=newSemaphore
(1);//通过
newThread(newRunnable(){
@Override
publicvoidrun(){
inti=1;
intj=1;
try{
System.out.println("已经签好名的书第"+i+"本");
arrayBlockingQueue.put("已经签好名的书第"+(i++)+"本");
/*System.out.println("已经签好名的书第"+i+"本");
arrayBlockingQueue.put("已经签好名的书第"+(i++)+"本");
System.out.println("已经签好名的书第"+i+"本");
arrayBlockingQueue.put("已经签好名的书第"+(i++)+"本");*/
while(true){
arrayBlockingQueue.put("签好名的书第"+j+"本");
System.out.println("签好名的书第"+(j++)+"本");
Thread.sleep(5000);
intnumber=arrayBlockingQueue.size();
System.out.println("签名售书-->队列中已经存在签好名的书"+number+"本了");
if(number==10){
System.out.println("签名售书-->队列中已经存在签好名的书10本了,作家可以休息了!
!
");
}
}
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}).start();
newThread(newRunnable(){
@Override
publicvoidrun(){
try{
for(inti=1;i<=5;i++){//假设有5个人排队、每个人买一本书
//semaphore.acquire();
intnumber=arrayBlockingQueue.size();
System.out.println("签名售书-->队列中已经存在签好名的书"+number+"本了");
if(number==0){
System.out.println("签名售书-->队列中已经不存签好名的书了,必须等待");
}
else
System.out.println("thread"+i+"拿走"
+arrayBlockingQueue.take());
Thread.sleep(3000);
//semaphore.release();
}
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}).start();
}
}
实验题5模拟拥有一定数量账户的银行,把随机产生的钱在不同账号之间进行转移交易。
每个账号都有一个线程,在每笔交易中,都会从线程所服务的账户中随机取出一定数额的钱转移到另一个随机账户中。
提示:
设计一个Bank类,它有一个transfer方法,该方法将一定数额的钱从一个账户转移到另一个账户,如源账户没有足够余额,该方法直接返回。
packagecn.edu.syn.banktransfer2.jp;
/**
Thisprogramshowshowmultiplethreadscansafelyaccessadatastructure,using
synchronizedmethods.
*/
publicclassSynchBankTest2
{
publicstaticvoidmain(String[]args)
{
Bankb=newBank(NACCOUNTS,INITIAL_BALANCE);
inti;
for(i=0;i { TransferRunnabler=newTransferRunnable(b,i,INITIAL_BALANCE); Threadt=newThread(r); t.start(); } } publicstaticfinalintNACCOUNTS=100; publicstaticfinaldoubleINITIAL_BALANCE=1000; } /** Abankwithanumberofbankaccounts. */ classBank { /** Constructsthebank. @paramnthenumberofaccounts @paraminitialBalancetheinitialbalance foreachaccount */ publicBank(intn,doubleinitialBalance) { accounts=newdouble[n]; for(inti=0;i accounts[i]=initialBalance; } /** Transfersmoneyfromoneaccounttoanother. @paramfromtheaccounttotransferfrom @paramtotheaccounttotransferto @paramamounttheamounttotransfer */ publicsynchronizedvoidtransfer(intfrom,intto,doubleamount) throwsInterruptedException { while(accounts[from] wait(); System.out.print(Thread.currentThread()); accounts[from]-=amount; System.out.printf("%10.2ffrom%dto%d",amount,from,to); accounts[to]+=amount; System.out.printf("TotalBalance: %10.2f%n",getTotalBalance()); notifyAll(); } /** Getsthesumofallaccountbalances. @returnthetotalbalance */ publicsynchronizeddoublegetTotalBalance() { doublesum=0; for(doublea: accounts) sum+=a; returnsum; } /** Getsthenumberofaccountsinthebank. @returnthenumberofaccounts */ publicintsize() { returnaccounts.length; } privatefinaldouble[]accounts; } /** Arunnablethattransfersmoneyfromanaccounttoother accountsinabank. */ classTransferRunnableimplementsRunnable { /** Constructsatransferrunnable. @parambthebankbetweenwhoseaccountmoneyistransferred @paramfromtheaccounttotransfermoneyfrom @parammaxthemaximumamountofmoneyineachtransfer */ publicTransferRunnable(Bankb,intfrom,doublemax) { bank=b; fromAccount=from; maxAmount=max; } publicvoidrun() { try { while(true) { inttoAccount=(int)(bank.size()*Math.random()); doubleamount=maxAmount*Math.random(); bank.transfer(fromAccount,toAccount,amount); Thread.sleep((int)(DELAY*Math.random())); } } catch(InterruptedExceptione){} } privateBankbank; privateintfromAccount; privatedoublemaxAmount; privateintrepetitions; privateintDELAY=10; } 3.实验总结 通过本次的实验,对线程应用及其并发库有了初步的认识。 对其相关的类和接口有了了解,总之,需要学习的东西还很多。
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 实验06 线程应用及线程并发库 实验 06 线程 应用 并发
![提示](https://static.bdocx.com/images/bang_tan.gif)