Java语言程序设计郑莉第八章课后习地的题目详解

上传人:z****2 文档编号:55774526 上传时间:2022-02-18 格式:DOC 页数:27 大小:147KB
返回 下载 相关 举报
Java语言程序设计郑莉第八章课后习地的题目详解_第1页
第1页 / 共27页
Java语言程序设计郑莉第八章课后习地的题目详解_第2页
第2页 / 共27页
Java语言程序设计郑莉第八章课后习地的题目详解_第3页
第3页 / 共27页
亲,该文档总共27页,到这儿已超出免费预览范围,如果喜欢就下载吧!
资源描述
Java语言程序设计第八章课后习题答案1. 进程和线程有何区别,Java是如何实现多线程的。答:区别:一个程序至少有一个进程,一个进程至少有一个线程;线程的划分尺度小于进程;进程在执行过程中拥有独立的内存单元,而多个线程共享内存, 从而极大地提高了程序的运行效率。Java程序一般是继承Thread类或者实现Runnable接口,从而实现多线程。2. 简述线程的生命周期,重点注意线程阻塞的几种情况,以及如何重回就绪状态。答:线程的声明周期:新建 -就绪-(阻塞)-运行-死亡线程阻塞的情况:休眠、进入对象wait池等待、进入对象lock池等待;休眠时间到回到就绪状态;在wait池中获得notify ()进入lock池,然后获得锁棋标进入就绪状态。3. 随便选择两个城市作为预选旅游目标。实现两个独立的线程分别显示10次城市名,每次显示后休眠一段随机时间(1000毫秒以内),哪个先显示完毕,就决定去哪个城市。分别 用Runnable 接口和Thread 类实现。(注:两个类,相同一个测试类)/Runn able接口实现的线程 run able 类public class runnable implements Runnable private String city ;publicrunn able() publicrunn able(Str ing city) this .city = city;public void run() for (int i = 0; i 10; i+) System. out .println( city );try /休眠1000毫秒。Thread. sleep (1000); catch (In terruptedExcepti on e) e.pri ntStackTrace();/ Thread 类实现的线程thread类public class runnableextends Thread privateString city ;public runn able() public runn able(Str ing city) this .city = city;public void run() for (int i = 0; i 10; i+) System. out .println( city );try /休眠1000毫秒。Thread. sleep (1000); catch (In terruptedExcepti on e) e.pri ntStackTrace();test8_3public class test8_3 public static void main( Stri ng args) Runnable接口。实际上这里也就/将创建一个线程对象,这个对象接受一个实现了是使用run()方法runnable r1=new runnable(广州);runnable r2=new runnable(乌鲁木齐);Thread t1 =new Thread(rl);Thread t2 =new Thread(r2);/启动线程t1.start();t2.start();运行结果分别为:Probftiru 而 Javadoc 屬 I testB_3 Java AppProblems 师 JavadocxlermETiated testB_3 Javi,乌曾木齐广州广州 马魯木界广閒马會木齐 广州乌曹木弃广州乌曾木齐 广州 马曽木齐广洲乌曹木界广的乌曾木界皆州曾洲 马广马广4编写一个多线程程序实现如下功能:线程A和线程B分别在屏幕上显示信息“start ”后,调用wait等待;线程C开始后调用sleep休眠一段时间,然后调用notifyall ,使线程A和线程B继续运行。线程 A和线程B恢复运行后输出信息“end ”后结束,线程 C在 判断线程B和线程A结束后自己结束运行。test8_4public class test8_4 Thread A = new Thread( A ) public void run() Wait( A);Thread B = new Thread( B ) public void run() Wait( B);;Thread C = new Thread( C) public void run() while (true ) if (!A.isAlive() & ! B.isAlive() return ;try Thread. sleep (2000); catch (In terruptedExcepti on e) e.pri ntStackTrace();n otifyall();public synchronizedvoid Wait(String name) System. out .println(name + .start);try wait(); catch (InterruptedException e) e.pri ntStackTrace();System. out .println(name +.end);publicsynchronizedvoid notifyall() n otifyAll();public static void main( Stri ng args) test8_4 test = new test8_4();/A、B两线程一起输入start和输岀end,不过中间有C让线程休眠2秒,没法全部一次 性输出,/之后再唤醒,让 AB继续输岀下半部分 endtest. A.start();test. B.start();test. C.start();运行结果:匕 Problems;tertnin3tedX 3rarE3- .srarcS, .end,end5.实现一个数据单元,包括学号和姓名两部分。编写两个线程,一个线程往数据单元中写,另一个线程往外读。要求没写一次就往外读一次。/Data 类public class DataString studentld ;String name ;boolean available = false ;/ 判断是读是写Scanner in = new Scanner(System.in);/ 定义一个输入对象public synchronizedvoid read()if (available )trywait();catch (Exception e)System. out .printf(请输入学号:);try studentld = in .next();catch (Exception e)System. out .println( “输入学号岀错!);System. out .printf(请输入姓名:); tryname = in .next();catch (Exception e)System. out .println( “输入姓名岀错!“);System. out .println();available = true ;n otify();public synchronizedvoid write()if (available )trywait();catch (Exception e)System. out .println( “输岀学生学号:+ studentld +姓名:+name + n);available = false ;n otify();/Read 类public class Read extends ThreadData di = null ;public Read(Data d)this .d1 =d;public void run()while (true )d1 .read();/Write 类class Write extends ThreadData d2 = null ;public Write(Data d)this .d2 =d;public void run()while (true )d2 .write();test8_5 类public class test8_5 public static void main( Stri ng args)Data data= new Data();new Read(data).start();new Write(data).start();运行结果:_ Problems住 Javadoc屬 DeclaraiJava /kpplicatior请输入学号:滴输入娃屯L-貫是输出字生学号;Mb垃害:林瓮金请输入学号:V清输入姓名;芒井空输岀学生学:ODG雄名:在#空,看看哪个数得快。6.创建两个不同优先级的线程,都从1数到10000(注:线程的优先级别越高低与执行速度没有绝对关系!Cou nt 类public class Count extendsThread int which int n = 10000;public Count( int which)this .which =which;public void run() for (int i = 1; i = n; i+) if (i = n) System. out .println( which +号进程+ 结束!);test8_6public class test8_6 public static void main( Stri ng args) Count cou nt1 =new Count(1);Count cou nt2 =new Count(2);Thread t1 = newThread(cou nt1);Thread t2 = newThread(cou nt2);t1.setPriority(2);/1号进程优先级是2t2.setPriority(8);/2号进程优先级是8t1.start();t2.start();运行结果:亡 Problems J tests2号进程结束I:LE遊穆结東I二 Problems.应上lernninjatedi tests.结束!直号邊程结束I都有可能7编写一个Java程序,以说明较高优先级的线程通过调用sleep程获得运行的机会。(这里可以借鉴课本例8 13)/TestThread 类public class TestThreadextends Thread private int tick = 1;private int num ;,使较低优先级的线public TestThread( int i) this .num = i;public void run() while (tick 400000) tick +;if (tick % 50000) = 0) System. out .println( Thread #+ num + , tick =+ tick );yield ();try sleep ; catch (Excepti on e) test8_7public class test8_7 public static void main( Stri ng args)TestThread runners = new TestThread2;for (int i=0;i2;i+)runnersi=new TestThread(i);ru nn ers0.setPriority(2);runn ers1.setPriority(5);for (int i=0;i testSr7 Java ppli匚活 1ThreadThread Thr e ad IJixeadTiireid Ihr ee:dThreadThreadTkre&d iTTireadThread Tiirtad Th-X-eadThread Thread Thre adriclr #0, tick 0, tick 壮匸让K 丰二! tick t:j, tick 4PL)ticSr *0,ricic #0, ticktickfo)tickcick tl,匸icic tli tick 顷 Tiek #1, tick=rSOOOQ =50000 -100000JGQG -150000 =150000 =200000 =200000 =250000 =250000 =300000 -350000 =300000 =350000 000Q0 =-(000008主线程控制新线程的生命,当主线程运行一段时间后,控制新线程死亡,主线程继续运行 一段时间后结束。(注:main函数就是主线程,程序里其他的 Thread都属于子线程。可以参考课本的例/So nThread类public classSon Thread exte nds Threadprivateint num ;public SonThread( int num)this .num =num;public void run()int i= numSystem. out .println(new thread start.);/* while(i0)*/result*i;System. out .println(the new thread of + num + is +result);System. out .println(new thread ends);test8_8public class test8_8 public static void main( Stri ng args)System. out .println( main tread start. );Son Thread n ewThread = new Son Thread(10); n ewThread.start();/ ;浪费时间的循环int i=1;while (i=100000)i+;newThread.stop();/ 结束新进程System. out .println( main thread ends );i Problemt奩Javadoc1=-Java A运行结果:(这个结果很难把握,ir.ain tread 邸七art,scar匸.n.ain thread 它Ed马通常都会出现2那样的结果,知道原理就好。)Problems 畅 J-suadot termnated testSB Jav main Dread STiart new 匸lread 出七注工匸. new thread main thread,另外一个9.用两个线程模拟存、取货物。一个线程往一对象里放货物(包括品名、价格) 线程取货物。分别模拟“放一个、取一个”和“放若干个、取若干个”两种情况。/Good 货物类public class Good String name ;int price ;public Good()public Good(String name,int price)this .name =name;this .price =price;public Good(Good g)this .name =g. name ;this .price =g. price ;/ WareHouse 仓库类public class WareHouse Good good = nullSeanner in = new Seanner(System.in);List list = new ArrayList(); / 用来存放商品对象int eount ;/想存入商品的个数boolea n available = truepublic WareHouse。public WareHouse( int eount) this .count = count;public WareHouse(List list) this .count = count ;for (int i = 0; i list.size(); i+) this .list .add(Good) list.get(i); public synchronizedvoid saveGood() if (available = false ) try wait(); catch (In terruptedExcepti on e) / TODO Auto-generated catch blocke.pri ntStackTrace();for (int i = 0; i count ; i+) Stri ng n;int p;System. out .println(请输入+ (i+1) +号商品的名称:);n = in .next();System. out .println(价格:);p = in.n extI nt();good = new Good(n, p);list .add( good );available = false ;n otify();public synchronizedvoid takeGood() if (available = true ) try wait(); catch (In terruptedExcepti on e) / TODO Auto-generated catch blocke.pri ntStackTrace();for (int i = 0; i list .size(); i+) good = (Good) list .get(i);.name );System. out .print(i+1)+号商品的名称为: + goodSystem. out .println( t 价格为:+ good .price );available = true ;n otify();/Save存货物类public class Save extends Thread WareHouse wareHouse = n ull public Save(WareHouse w) this .wareHouse =w;public void run()wareHouse .saveGood();/Take取货物类 public class Take extends ThreadWareHouse wareHouse = n ullpublic Take(WareHouse w)this .wareHouse =w;public void run()wareHouse .takeGood();test8_9 测试类public class test8_9 public static void main( Stri ng args)Scanner in = new Scanner(System.in);System. out .println(请输入仓库的容量:);int i=in.nextInt();WareHouse wareHouse= new WareHouse(i);Thread saveGood=new Save(wareHouse);Thread takeGood=new Take(wareHouse);saveGood.start();takeGood.start();运行结果:1 Pro-blems 篠 Javadoc .自Declaration 国 C test8_9 Java Application D:PrOg诵输入仓臨的咨里;Ji诸输入三号崗抽勺名称:5 片厂r戸,4二号苗品的容称为;ipone4估搐为;50001 Problems 怎 Javadoc 住 Declarartian 曰匚匚卍Java Applkti口fi D;Program请输入仓库的容更;iSfiAi号商品名釈 |苍井空全集请输入h号询品勺名称:黑人牙肓右请输入3号询丘的椒火疋忍奢漫 画情格:?25I号商品的名称为:卷井空全枭 价格為吃50 3号商品的茗耕为;契人牙昔侑格拘:石d号商品的名称为;火影忍者漫画价格芮;左210.用两个线程模拟对话,任何一个线程都可以随时收发信息。(这道题本人搞不清楚,暂且用网上的给大家参考下。 听说要用到:Socket.getl nputStream()获取输入流用于接收”Socket.getOutputStream()获取输出流用于发送”test8_10importjava.io.*;importjava .n et.*;importjava.util.*;publicclass test8_10 public static void main( Stri ng args) try / establish server socketServerSocket s = new ServerSocket(8189);/ wait for clie nt conn ecti onSocket incoming = s.accept();try In putStream in Stream = incomin g.get In putStream();OutputStream outStream = in comi ng.getOutputStream();Scanner in = new Scanner(inStream);PrintWriter out =new PrintWriter(outStream,true );out.pr intln(Hello! En ter BYE to exit.);/ echo client in putbooleandone = false ;while (!do ne & in .hasNextLi ne() String line = in.nextLine();out.pri ntln( Echo: + lin e);if (line.trim().equals( BYE) done = true ; fin allyincomin g.close(); catch (IOExcepti on e) e.pri ntStackTrace();
展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 办公文档 > 活动策划


copyright@ 2023-2025  zhuangpeitu.com 装配图网版权所有   联系电话:18123376007

备案号:ICP2024067431-1 川公网安备51140202000466号


本站为文档C2C交易模式,即用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知装配图网,我们立即给予删除!