<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    我思故我強

    第七部分:線程

    第七部分:線程

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

    §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)

     

      題目:有關線程的哪些敘述是對的。

     

      A. 一旦一個線程被創建,它就立即開始運行。

     

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

     

      C. 當一個線程因為搶先機制而停止運行,它被放在可運行隊列的前面。

     

      D. 一個線程可能因為不同的原因停止(cease)并進入就緒狀態。

     

      一個新創建的線程并不是自動的開始運行的,必須調用它的start()方法使之將線程放入

    可運行態(runnable

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

    線程的調度是搶先式的,而不是分時間片式的。具有比當前運行線程高優先級的線程可以使當

    前線程停止運行而進入就緒狀態,不同優先級的線程間是搶先式的,而同級線程間是輪轉式的

    。一個線程停止運行可以是因為不同原因,可能是因為更高優先級線程的搶占,也可能是因為

    調用sleep()方法,而即使是因為搶先而停止也不一定就進入可運行隊列的前面,因為同級線

    程是輪換式的,它的運行可能就是因為輪換,而它因搶占而停止后只能在輪換隊列中排隊而不

    能排在前面。

     

    §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 李云澤 閱讀(685) 評論(0)  編輯  收藏 所屬分類: 面試筆試相關的SCJP認證學習

    主站蜘蛛池模板: 伊人亚洲综合青草青草久热| 又大又硬又爽免费视频| 人人狠狠综合久久亚洲88| 成人免费夜片在线观看| www国产亚洲精品久久久日本| WWW国产亚洲精品久久麻豆| 日本大片在线看黄a∨免费| 亚洲AV无码一区二区三区电影| 无码高潮少妇毛多水多水免费| 亚洲熟女乱色一区二区三区| 性一交一乱一视频免费看| 亚洲精品无码mⅴ在线观看| 午夜影视在线免费观看| 黄页网站在线免费观看| 国产亚洲人成A在线V网站 | 亚洲精品乱码久久久久久蜜桃| 添bbb免费观看高清视频| 亚洲AV无码一区二区三区在线观看| 永久免费无码网站在线观看个| 亚洲线精品一区二区三区影音先锋 | 免费国产黄网站在线观看动图| 亚洲精品亚洲人成在线观看下载| 草久免费在线观看网站| 亚洲国产第一站精品蜜芽| h片在线免费观看| 色噜噜的亚洲男人的天堂| 亚洲精品一品区二品区三品区| 中文字幕在线免费观看| 亚洲www在线观看| 久久久精品国产亚洲成人满18免费网站| 中文字幕乱码一区二区免费| 亚洲成电影在线观看青青| 日本一区二区三区日本免费| 久草免费福利在线| 亚洲国产中文在线二区三区免| 免费a级毛片无码a∨性按摩| 久久精品国产免费一区| 亚洲精品av无码喷奶水糖心| 中文字幕久久亚洲一区| 18pao国产成视频永久免费| 国产亚洲综合精品一区二区三区|