我思故我強(qiáng)

          第七部分:線程

          第七部分:線程

          • 能用java.lang,Thread或java.lang.Runnable兩種方法定義,實(shí)例化和開始一個(gè)新的線程。
          • 知道哪些情況下可能阻止一個(gè)線程的執(zhí)行。
          • 能使用synchronized,wait,notify和notifyAll去避免并發(fā)訪問的問題,以及線程間相互通訊的問題。
          • 當(dāng)執(zhí)行synchronized,wait,notify和notifyAll時(shí),知道線程和對(duì)象鎖之間的交互作用。

          §1.1.1    

          What will happen when you attempt to compile and run the following code?

          class MyThread extends Thread

          {

          public void run()

          {

          System.out.println("MyThread: run()");

          }

          public void start()

          {

          System.out.println("MyThread: start()");

          }

          }

          class MyRunnable implements Runnable

          {

          public void run()

          {

          System.out.println("MyRunnable: run()");

          }

          public void start()

          {

          System.out.println("MyRunnable: start()");

          }

          }

          public class MyTest

          {

          public static void main(String args[])

          {

          MyThread myThread  =  new MyThread();

          MyRunnable myRunnable = new MyRunnable();

          Thread thread  =  new Thread(myRunnable);

          myThread.start();

          thread.start();

          }

          }

          Choices:

          a. Prints : MyThread: start() followed by MyRunnable:run()

          b. Prints : MyThread: run() followed by MyRunnable:start()

          c. Prints : MyThread: start() followed by MyRunnable:start()

          d. Prints : MyThread: run() followed by MyRunnable:run()

          e. Compile time error

          f. None of the above

          ―――――――――――――――

          A is the correct choice. In the above code there is not any compilation error. Thus choice E is incorrect. Inside main() method, objects of MyThread and MyRunnable class are created followed by creation of Thread with object of MyRunnable class. Note that MyThread class extends Thread class and overrides the start() method of the Thread class. Thus on execution of "myThread.start()" statement, the start() method of the MyThread class will be executed and as a result "MyThread:start()" will be printed. Had the start() method not there in MyThread class, the start() method of the Thread class would be called which in turn would call the run() method of the MyThread class. On execution of "thread.start();", the start() method of the Thread class would be called which in turn will call the run() method of the class which is passed to Thread constructor (i.e. MyRunnable class). Thus "MyRunnable:run()" will be printed out. Thus choice A is correct.

           

          §1.1.2      

          What will be the output on compiling/running the following code?

          public class MyThread implements Runnable

          {

            String myString = "Yes ";

            public void run()

            {

              this.myString = "No ";

            }

            public static void main(String[] args)

            {

              MyThread t = new MyThread();

              new Thread(t).start();

              for (int i=0; i < 10; i++)

               System.out.print(t.myString);

            }

          }

          Choices:

          a. Compilation Error  

          b. Prints : Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes and so on.

          c. Prints : No No No No No No No No No No and so on.

          d. Prints : Yes No Yes No Yes No Yes No Yes No and so on.

          e. The Output cannot be determined.

          E is correct. Please note that there will not be any compilation error when the above code is compiled. Also note that calling start() method on a Thread doesn't start the Thread. It only makes a Thread ready to be called. Depending on the operation system and other running threads, the thread on which start is called will get executed. In the above case it is not guaranteed that the thread will be executed(i.e. run() method will be called), always before "for" loop is executed. Thus the output cannot be determined.

           

          §1.1.3      

          Multiple objects of MyClass (given below) are used in a program that uses

          multiple Threadsto create new integer count. What will happen when other threads

          use the following code?

          class MyClass

          {

          static private int myCount = 0;

          int yourNumber;

          private static synchronized int nextCount()

          {

          return ++myCount;

          }

          public void getYourNumber()

          {

          yourNumber = nextCount();

          }

          }

          Choices:

          a. The code will give compilation error.

          b. The code will give runtime error.

          c. Each thread will get a unique number.

          d. The uniqueness of the number among different Threads can't be guaranteed.

          ―――――――――――――

          C is correct. The use of synchronized ensures that the number generated will not be duplicated, no matter how many Threads are trying to create the number. Thus D is incorrect. A and B are incorrect as the above code will not give any compiletime or runtime error.

          §1.1.4      

          What will happen when you attempt to compile and run the following code?

          public class MyThread extends Thread

          {

          String myName;

          MyThread(String name)

          {

          myName = name;

          }

          public void run()

          {

          for(int i=0; i<100;i++)

          {

          System.out.println(myName);

          }

          }

          public static void main(String args[])

          {

          try

          {

          MyThread mt1 = new MyThread("mt1");

          MyThread mt2 = new MyThread("mt2");

          mt1.start();

          // XXX

          mt2.start();

          }

          catch(InterruptedException ex)

          {

          }

          }

          }

          Choices:

          a.The above code in its current condition will not compile.

          b. In order to make the MyThread class prints "mt1" (100 times) followed by

          "mt2" (100 times), mt1.join(); can be placed at //XXX position.

          c. In order to make the MyThread class prints "mt1" (100 times) followed by

          "mt2" (100 times), mt1.sleep(100); can be placed at //XXX position.

          d. In order to make the MyThread class prints "mt1" (100 times) followed by

          "mt2" (100 times), mt1.run(); can be placed at //XXX position.

          e. In order to make the MyThread class prints "mt1" (100 times) followed by

          "mt2" (100 times), there is no need to write any code.

          ――――――――――――――

          A and B are correct. In its current condition, the above code will not compile as "InterruptedException" is never thrown in the try block. The compiler will give following exception: "Exception java.lang.InterruptedException is never thrown in the body of the corresponding try statement." Note that calling start() method on a Thread doesn't start the Thread. It only makes a Thread ready to be called. Depending on the operating system and other running threads, the thread on which start is called will get executed. After making the above code to compile (by changing the InterruptedException to some other type like Exception), the output can't be predicted (the order in which mt1 and mt2 will be printed can't be guaranteed). In order to make the MyThread class prints "mt1" (100 times) followed by "mt2" (100 times), mt1.join() can be placed at //XXX position. The join() method waits for the Thread on which it is called to die. Thus on calling join() on mt1, it is assured that mt2 will not be executed before mt1 is completed. Also note that the join() method throws InterruptedException, which will cause the above program to compile successfully. Thus choice A and B are correct.

           

          §1.1.5      

          What will happen when you attempt to compile and run the following code?

          public class MyThread extends Thread{

          String myName;

          MyThread(String name){

          myName = name;

          }

          public void run(){

          for(int i=0; i<100;i++){

          System.out.println(myName);

          }

          }

          public static void main(String args[]){

          try{

          MyThread mt1 = new MyThread("mt1");

          MyThread mt2 = new MyThread("mt2");

          mt1.start();

          // XXX

          mt2.start();

          }catch(InterruptedException ex){}

          }

          }

          A. compile error

          B. mt1.join();

          C. mt1.sleep(100);

          D. mt1.run()

          E. nothing need

           

          Choice A and B are correct. In its current condition, the above code will not compile as "InterruptedException" is never thrown in the try block. The compiler will give following exception: "Exception java.lang.InterruptedException is never thrown in the body of the corresponding try statement."

          Note that calling start() method on a Thread doesn't start the Thread. It only makes a Thread ready to be called. Depending on the operating system and other running threads, the thread on which start is called will get executed. After making the above code to compile (by changing the InterruptedException to some other type like Exception), the output can't be predicted (the order in which mt1 and mt2 will be printed can't be guaranteed). In order to make the MyThread class prints "mt1" (100 times) followed by "mt2" (100 times), mt1.join() can be placed at //XXX position. The join() method waits for the Thread on which it is called to die. Thus on calling join() on mt1, it is assured that mt2 will not be executed before mt1 is completed. Also note that the join() method throws InterruptedException, which will cause the above program to compile successfully. Thus choice A and B are correct.

          §1.1.6      

          Multiple objects of MyClass (given below) are used in a program that uses multiple Threads to create new integer count. What will happen when other threads use the following code?

          class MyClass{

          static private int myCount = 0;

          int yourNumber;

          private static synchronized int nextCount(){

          return ++myCount;   //myCount為static

          }

          public void getYourNumber(){

          yourNumber = nextCount();

          }

          }

          A. the code ill give ompilation error

          B. the code ill give runtime error

          C. each thread will get a unique number

          D. the uniqueness of the number different Threads can’t be guaranteed.

           

          C is correct. The use of synchronized ensures that the number generated will not be duplicated, no matter how many Threads are trying to create the number. Thus D is incorrect. A and B are incorrect as the above code will not give any compiletime or runtime error.

           

          §1.1.7      

          What will be the output on compiling/running the following code?

          public class MyThread implements Runnable {

            String myString = "Yes ";

            public void run() {

              this.myString = "No ";

            }

            public static void main(String[] args)  {

              MyThread t = new MyThread();

              new Thread(t).start();

              for (int i=0; i < 10; i++)

               System.out.print(t.myString);

            }

          }

          A. compile error

          B. prints: yes yes yes yes yes yes and so on

          C. prints: no no no no no no no no and so on

          D. prints: yes no yes no ye no ye no and so on

          E. the output cannot be determinated

           

          E is correct. Please note that there will not be any compilation error when the above code is compiled. Also note that calling start() method on a Thread doesn't start the Thread. It only makes a Thread ready to be called. Depending on the operation system and other running threads, the thread on which start is called will get executed. In the above case it is not guaranteed that the thread will be executed(i.e. run() method will be called), always before "for" loop is executed. Thus the output cannot be determined.

          §1.1.8      

          Which statements about thread are true?

            A. Once a thread is created, it can star running immediately.

           

            B. To use the start() method makes a thread runnable, but it does not

          necessarily start immediately.

           

            C. When a thread stops running because of pre-emptive, it is placed at

          the front end of the runnable queue.

           

            D. A thread may cease to be ready for a variety of reasons.

           

            (bd)

           

            題目:有關(guān)線程的哪些敘述是對(duì)的。

           

            A. 一旦一個(gè)線程被創(chuàng)建,它就立即開始運(yùn)行。

           

            B. 使用start()方法可以使一個(gè)線程成為可運(yùn)行的,但是它不一定立即開始運(yùn)行。

           

            C. 當(dāng)一個(gè)線程因?yàn)閾屜葯C(jī)制而停止運(yùn)行,它被放在可運(yùn)行隊(duì)列的前面。

           

            D. 一個(gè)線程可能因?yàn)椴煌脑蛲V梗╟ease)并進(jìn)入就緒狀態(tài)。

           

            一個(gè)新創(chuàng)建的線程并不是自動(dòng)的開始運(yùn)行的,必須調(diào)用它的start()方法使之將線程放入

          可運(yùn)行態(tài)(runnable

          state),這只是意味著該線程可為JVM的線程調(diào)度程序調(diào)度而不是意味著它可以立即運(yùn)行。

          線程的調(diào)度是搶先式的,而不是分時(shí)間片式的。具有比當(dāng)前運(yùn)行線程高優(yōu)先級(jí)的線程可以使當(dāng)

          前線程停止運(yùn)行而進(jìn)入就緒狀態(tài),不同優(yōu)先級(jí)的線程間是搶先式的,而同級(jí)線程間是輪轉(zhuǎn)式的

          。一個(gè)線程停止運(yùn)行可以是因?yàn)椴煌?,可能是因?yàn)楦邇?yōu)先級(jí)線程的搶占,也可能是因?yàn)?/p>

          調(diào)用sleep()方法,而即使是因?yàn)閾屜榷V挂膊灰欢ň瓦M(jìn)入可運(yùn)行隊(duì)列的前面,因?yàn)橥?jí)線

          程是輪換式的,它的運(yùn)行可能就是因?yàn)檩啌Q,而它因搶占而停止后只能在輪換隊(duì)列中排隊(duì)而不

          能排在前面。

           

          §1.1.9      

          Which two CANNOT directly cause a thread to stop executing? (Choose Two)

           

          A.Existing from a synchronized block

          B.Calling the wait method on an object

          C.Calling notify method on an object

          D.Calling read method on an InputStream object

          E.Calling the SetPriority method on a Thread object

          Answer:AC。同55題

           

          §1.1.10 十

           public class SyncTest{

           public static void main(String[] args)  {

           final StringBuffer s1= new StringBuffer();

           final StringBuffer s2= new StringBuffer();

           new Thread ()   {

             public void run() {

               synchronized(s1) {

                   s2.append(“A”);

                    synchronized(s2) {

             s2.append(“B”);

               System.out.print(s1);

                 System.out.print(s2);

                }

               }

             

           }.start();

           new Thread() {

             public void run() {

               synchronized(s2) {

                 s2.append(“C”);

                 synchronized(s1) {

                  s1.append(“D”);

                   System.out.print(s2);

                   System.out.print(s1);

                  }

                }

                }

              }.start();

             }

           }

          Which two statements are true? (Choose Two)

          A. The program prints “ABBCAD”

          B. The program prints “CDDACB”

          C. The program prints “ADCBADBC”

          D. The output is a non-deterministic point because of a possible deadlock condition

          E. The output is dependent on the threading model of the system the program is running on.

          Answer:DE

           

          §1.1.11 十一

          What will happen when you attempt to compile and run the following code?

          public class Test{  

             int i = 0;  

             public static void main(String argv[]) {      

               Test t = new Test();      

               t.myMethod();  

             

             public void myMethod(){       

               while(true) {          

                           try {               

                             wait();          

                           }catch (InterruptedException e) {}          

                           i++;      

               

             }

          }

          A. Compile time error, no matching notify within the method.

          B. Compile and run but an infinite looping of the while method.

          C. Compilation and run without any output.

          E. Runtime Exception "IllegalMonitorStatException".

          Answer: E

          Note: The wait/notify protocol can only be used within code that is synchronized. In this case calling code does not have a lock on the object(not synchronized) and will thus cause an Exception at runtime.

           

          §1.1.12 十二

          1.10 What is the result of compiling and executing the following code?

          public class ThreadTest extends Thread { 

               public void run() {     

                           System.out.println("In run");     

                           yield();    

                           System.out.println("Leaving run"); 

               

               public static void main(String args []) {  

                           (new ThreadTest()).start(); 

               }

          }

          A. The code fails to compile in the main() method.

          B. The code fails to compile in the run() method.

          C. Only the text "In run" will be displayed.

          D. The text "In run" followed by "Leaving run" will be displayed.

          E. The code compiles correctly, but nothing is displayed.

          Answer: D

           

          §1.1.13 十三

          Which of the following will definitely stop a thread from executing?A. wait()B. notify()C. yield()D. suspend()E. sleep()Answer: ACDE

           

          §1.1.14 十四

          Which of the following will definitely stop a thread from executing?

          A. wait()

          B. notify()

          C. yield()

          D. suspend()

          E. sleep()

          Answer: ACDE

           

          §1.1.15 十五

           Which of the following statements about threading are true?

          A. You can only obtain a mutually exclusive lock on methods in a class that extends Thread or implements runnable.

          B. You can obtain a mutually exclusive lock on any object.

          C. You can't obtain a mutually exclusive lock on any object.

          D. Thread scheduling algorithms are platform dependent.

          Answer: BD

          8:

          Consider the following statement:  

          Thread myThread = new Thread();

          Which of the following statements are true regarding myThread?

          A. The thread myThread is now in a runnable state.

          B. The thread myThread has a priority of 5.

          C. On calling the start() method on myThread, the run method in the Thread class will be executed.

          D. On calling the start() method on myThread, the run method in the calling class will be executed.

          Answer: C

          Note: the priority of myThread will be inherited from the Thread that called the constructor.

          §1.1.16 十六

          What is the effect of issuing a wait() method on an object?(Mutiple)

          1) If a notify() method has already been sent to that object then it has no effect

          2) The object issuing the call to wait() will halt until another object sends a notify() or notifyAll() method

          3) An exception will be raised

          4) The object issuing the call to wait() will be automatically synchronized with any other objects using the receiving object.

          ANSWER 1)

          10:

          Pick all the true statements below.

          1) If a thread wants to call wait() on an object, the thread must own that object's lock.

          2) There is a method that you can call on an instance of the Thread class that puts the instance to sleep for a specified    number of milliseconds.

          3) At the moment when a thread is notified, it automatically gets the lock of the object for which it was waiting.

          ANSWER 1

           

          posted on 2009-10-16 11:43 李云澤 閱讀(689) 評(píng)論(0)  編輯  收藏 所屬分類: 面試筆試相關(guān)的 、SCJP認(rèn)證學(xué)習(xí)

          主站蜘蛛池模板: 景谷| 承德市| 余干县| 凭祥市| 平舆县| 锦州市| 田东县| 华蓥市| 华亭县| 汽车| 武夷山市| 上思县| 拜城县| 华坪县| 临夏市| 特克斯县| 蒲城县| 英德市| 镇江市| 龙江县| 六安市| 阿拉善右旗| 蒙城县| 巍山| 东平县| 武安市| 永昌县| 三明市| 平昌县| 陵水| 宿松县| 惠州市| 班戈县| 杭锦旗| 永丰县| 昭平县| 中方县| 大英县| 永顺县| 桂东县| 广东省|