您好,欢迎访问三七文档
第八章Java多线程技术1、程序如下:publicclassBorleyextendsThread{publicstaticvoidmain(String[]argv){Borleyb=newBorley();b.start();}publicvoidrun(){System.out.println(Running);}}下面描述正确的是:(B)单选A)通过编译和运行但是没有任何输出。B)通过编译,运行后输出RunningC)编译出错,没有线程可供运行D)编译出错,没有权限使用Thread2、编写程序,启动1000个线程,每个线程给初值为0的变量sum加1。(提示,需要通过引用传递,将sum传递给每个线程,为了能够进行引用传递,需要定义一个Integer包装对象来保存sum)。publicclassTreadTestimplementsRunnable{privatestaticintsum=0;privatestaticintcount=0;publicvoidrun(){adds();}publicTreadTest(intcounttemp){count=counttemp+1;}synchronizedpublicstaticvoidadds(){++sum;System.out.println(线程+count+sum值+sum);}publicstaticvoidmain(String[]args){Threadtest=null;for(inti=0;i1000;i++){test=newThread(newTreadTest(i));test.start();}System.out.println(sum的值+sum+);}}3、利用多线程技术模拟龟兔赛跑的场面。提示:先设计一个线程类模拟两个参与赛跑的选手的行为;然后创建该类的两个对象分别代表乌龟和兔子;让兔子跑快些,但在路上睡眠休息时间长些,而乌龟跑慢些却不休息;当某个选手到达终点时其线程运行结束;二个选手均到达终点时,显示并祝贺获胜选手,然后主线程结束。publicclassT{publicstaticvoidmain(String[]args){TortoiseRacea=newTortoiseRace();Threadrunner1=newThread(a);RabbitRaceb=newRabbitRace();Threadrunner2=newThread(b);runner1.start();runner2.start();while(ready2){try{Thread.sleep(1);}catch(InterruptedExceptione){e.printStackTrace();}}synchronized(lock){lock.notifyAll();}}staticObjectlock=newObject();staticintready=0;}classTortoiseRaceimplementsRunnable{@Overridepublicvoidrun(){synchronized(T.lock){T.ready++;try{T.lock.wait();}catch(InterruptedExceptione1){e1.printStackTrace();}}intTortoiseDistance=0;for(inti=0;TortoiseDistance=10;i++){TortoiseDistance++;System.out.println(乌龟跑了1米!);try{Thread.sleep(1);}catch(InterruptedExceptione){}}System.out.println(乌龟已经跑完了比赛路程!);}}classRabbitRaceimplementsRunnable{@Overridepublicvoidrun(){T.ready++;synchronized(T.lock){try{T.lock.wait();}catch(InterruptedExceptione1){e1.printStackTrace();}}intRabbitDistance=0;for(intj=0;RabbitDistance=10;j++){RabbitDistance+=5;System.out.println(兔子跑了5米!);try{Thread.sleep(10);}catch(InterruptedExceptione){}}System.out.println(兔子跑完了比赛路程!);}}
本文标题:java-作业八
链接地址:https://www.777doc.com/doc-4882482 .html