close

建立執行緒步驟:

第一種作法 :
1. 撰寫Thread的子類別, 並override run() method
2. new 步驟1的class之實體
3. 呼叫步驟2實體中的start()

第二種作法 :
1. 撰寫一新類別並實作java.lang.Runnable介面
2. new Thread(new 步驟1的class之實體)
3. 呼叫步驟2實體中的start()

 

ThreadTestMain.java

package com.hellopianoman.thread;

public class ThreadTestMain {
    public static void main(String[] args) {
        ShowDataThread showDataThread = new ShowDataThread();
        showDataThread.start();

        GetDataThread getDataThread = new GetDataThread(showDataThread);
        getDataThread.start();
    }
}

 

GetDataThread.java

package com.hellopianoman.thread;

public class GetDataThread extends Thread {

    private ShowDataThread showDataThread;

    public GetDataThread(ShowDataThread showDataThread) {
        this.showDataThread = showDataThread;
    }

    @Override
    public void run() {

        while (true) {
            // 同步化處理
            synchronized(String.class) { //或是寫成 synchronized(showDataThread) {
                if (Math.random() > 0.5) {
                    Product p = new Product("黃金", 1462 + Math.random() * 10);
                    showDataThread.addData(p);
                }

                if (Math.random() > 0.5) {
                    Product p = new Product("白金", 24 + Math.random() * 10);
                    showDataThread.addData(p);
                }
                if (Math.random() > 0.5) {
                    Product p = new Product("石油", 62 + Math.random() * 10);
                    showDataThread.addData(p);
                }
            }
        }

    }
}

 

ShowDataThread.java

package com.hellopianoman.thread;

import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ShowDataThread extends Thread {

    private ArrayList<Product> data = new ArrayList<Product>();

    @Override
    public void run() {
        while (true) {

            synchronized (this) {
                try {
                    data.wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(ShowDataThread.class.getName()).log(Level.SEVERE, null, ex);
                }

                for (Product p : data) {
                    // System.out.println("商品名稱:"+p.getName()+",商品價格:"+p.getPrice());
                    System.out.printf("商品名稱:%s, 商品價格:%.2f %n", p.getName(), p.getPrice());
                }
                System.out.println();
                data.clear();
            }
        }
    }

    public void addData(Product product) {
        data.add(product);
    }
}

考古題:

public class Test implements Runnable {
  public void run() {
    System.out.print("running");
  }

  public static void main(String[] args) {
    Thread t = new Thread(new Test());
    t.run();
    t.run();
    t.start();
  }
}
What is the result ?


A. compilation fails
B. an exception is thrown at runtime
C. the code executes and prints "running"
D. the code executes and prints "runningrunning"
E. the code executes and prints "runningrunningrunning"


答案: E

 

public class Thread2 implements Runnable {
  public void run() {
    System.out.println("run.");
    throw new RuntimeException("Problem");
  }
  public static void main(String[] args) {
    Thread t=new Thread(new Thread2());
    t.start();
    System.out.println("End of method.");
  }
}

Which two can be results? (Choose two.)


A. java.lang.RuntimeException: Problem
B. run.   java.lang.RuntimeException: Problem
C. End of method.   java.lang.RuntimeException: Problem
D. End of method.   run.   java.lang.RuntimeException: Problem
E. run.   java.lang.RuntimeException: Problem   End of method


答案: DE

 

public class Test {
  public static void main(String[] args) throws Exception {
    Thread.sleep(3000);
    System.out.println("sleep");
  }
}

What is the result ?


A. compilation fails
B. an exception is thrown at runtime
C. the code executes normally and prints "sleep"
D. the code executes normally, but nothing is printed


答案: C

 

void waitForSignal() throws InterruptedException {
  Object obj=new Object();
  synchronized(Thread.currentThread()) {
     obj.wait();
     obj.notify();
  }
}

What's the result ?


A. this code may throw an InterruptedException
B. this code may throw an IllegalMonitorStateException
C. This code may throw a TimeoutException after ten minutes.
D. This code will not compile unless obj.wait() is replaced with((Thread) obj).wait().
E. Reversing the order of obj.wait() and obj.notify() may cause this method to complete normally.
F. A call to notify() or notifyAll() from another thread may cause this method to complete normally.


答案: B,第3行鎖拿錯或沒寫,編譯會過,但執行時期會出錯"IllegalMonitorStateException。

 

Which two code fragment will execute the method doStuff() in a separate thread ? (choose two)


A. new Thread() {     public void run() { doStuff(); }   };
B. new Thread() {     public void run() { doStuff(); }   }.run();
C. new Thread() {     public void run() { doStuff(); }   }.start();
D. new Thread(new Runnable() {     public void run() { doStuff(); }   }).run();
E. new Thread(new Runnable() {     public void run() { doStuff(); }   }).start();


答案: CE, 要建立執行緒一定要有Start

 

public class TestOne implements Runnable {
  public static void main(String[] args) throws Exception {
    Thread t=new Thread(new TestOne());
    t.start();
    System.out.print("Started");
    t.join();
    System.out.print("Complete");
  }

  public void run() {
    for(int i=0; i<4; i++)
      System.out.print(i);
  }
}
What can be a result ?


A. compilation fails
B. an exception is thrown at runtime
C. the code executes and prints "StartedComplete"
D. the code executes and prints "StartedComplete0123"
E. the code executes and prints "Started0123Complete"


答案: E

 

Which three will compile and run without exception ? (choose three)


A. private synchronized Object o;
B. void go() { synchronized(){ /* code here*/ } }
C. public synchronized void go() { /*code here*/ }
D. private synchronized(this) void go() { /*code here*/ }
E. void go() { synchronized(Object.class) { /*code here*/ } }
F. void go() { synchronized(o) { /*code here*/ } }


答案:CEF

 

public class NamedCounter {
  private final String name;
  private int count;
  public NamedCounter(String name) { this.name=name; }
  public String getName() { return name; }
  public void increment() { count++; }
  public int getCount() { return count; }
  public void reset() { count=0; }
}

Which three changes should be made to adapt this class to be used safely by multiple threads? (Choose three.)


A. declare reset() using the synchronized keyword
B. declare getName() using the synchronized keyword
C. declare getCount() using the synchronized keyword
D. declare the constructor using the synchronized keyword
E. declare increment() using the synchronized keyword


答案: ACE,跟count有關的

 

1. public class SyncTest{
2.  public static void main(String[] args){
3.  final StringBuffer s1 = new StringBuffer();
4.   final StringBuffer s2 = new StringBuffer();
5.   new Thread (){
6.   public void run(){
7.    synchronized(s1){
8.      s2.append("A");
9.     synchronized(s2){
10.       s2.append("B");
11.      System.out.print(s1);
12.      System.out.print(s2);
13.      }
14.     }
15.    }
16.   }.start();
17.   new Thread(){
18.    public void run(){
19.     synchronized(s2){
20.     s2.append("C");
21.      synchronized(s1){
22.       s1.append("D");
23.       System.out.print(s2);
24.      System.out.print(s1);
25.      }
26.    }
27.    }
28.  }.start();
29. }
30.}

Which statements are true?


A. The program prints "ABBCAD"
B. The program prints "CDDCAB"
C. The program prints "ADCBADBC"
D. The output is a non-deterministic point because of a possible deadlock condition


答案: D,鎖死。

 

 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 鈴木保齡球 的頭像
    鈴木保齡球

    Java程式學習手札

    鈴木保齡球 發表在 痞客邦 留言(1) 人氣()