1. 程式人生 > >一次面試

一次面試

年前最後一次面試,做了一套面試題。那套題真是獨闢蹊徑,至今想來尤覺得還有沒發現的。記憶最深的是一道是程式設計題:操作執行緒,順序輸出10101010...

乍一看來這道題無從下手,因為執行緒的執行時無序的。但通過生產者消費者執行緒可以達到這種效果:我的實現是


public class TestThread {
 public static void main(String[] args){
  MyInte mi=new MyInte(0);
  Thread t1=new ThreadA(mi);
  Thread t2=new ThreadB(mi);
  t1.start();
  t2.start();
 }
 
}
class MyInte{
 private int i;
 public MyInte(int i){
  this.i=i;
 }
 public synchronized void add(){
  while(true){
   while(i==0){
    this.i++;
    String str="加:";
    print(str);
    this.notifyAll();
   }
   try {
    this.wait();
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
 public synchronized void reduce(){
  while(true){
   while(i==1){
    this.i--;
    String str="減:";
    print(str);
    this.notifyAll();
   }
   try {
    this.wait();
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
 private void print(String str){
  System.out.println(str+this.i);
 }
}
class ThreadA extends Thread{
 private MyInte i;
 public ThreadA(MyInte i){
  this.i=i;
 }
 public void run(){
  i.add();
 }
}
class ThreadB extends Thread{
 private MyInte i;
 public ThreadB(MyInte i){
  this.i=i;
 }
 public void run(){
  i.reduce();
 }
}

仔細想來,這道題的要點是生產者也是消費者,同樣消費者也是生產者。

還有幾道比較好的題,無奈隔得太久了,都記不清了。