一次面试

年前最后一次面试,做了一套面试题。那套题真是独辟蹊径,至今想来尤觉得还有没发现的。记忆最深的是一道是编程题:操作线程,顺序输出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();
 }
}

仔细想来,这道题的要点是生产者也是消费者,同样消费者也是生产者。

还有几道比较好的题,无奈隔得太久了,都记不清了。

猜你喜欢

转载自blog.csdn.net/sjc106112/article/details/5495617
今日推荐