我思故我强

第七部分:线程

第七部分:线程

  • 能用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 李云泽 阅读(661) 评论(0)  编辑  收藏 所属分类: 面试笔试相关的SCJP认证学习


只有注册用户登录后才能发表评论。


网站导航: