去笔试遇到2道题让我很无奈啊。看看有高手解答不,长长见识。
       
      1.实现一个排序方法,能对任意复合类型数组排序.比如Intger[],String[],Long[]或者其他任意类型的数组. 代码不做限制可随意发挥(谢绝调用API方法).
      2.修改bug:下面代码无法每次执行都按照正确的顺序输出0,1,2….20,请使用synchronized关键字修改代码,让代码每次执行都能按照正确的顺序输出0,1,2….20(不能增删其他代码).并阐述修改理由.
 
      public final class Count
{
/* static fields */
public static final Count count=new Count();

/*fields */
int i;

/* constructor */
private Count()
{
}

/* properties */
public int getCount()
{
return i;
}

/* methods */
public void add()
{
i++;
}
public boolean isContinue()
{
return i<=20;
}
}public class PrintA implements Runnable
{ /* fields */
Count count; /* properties */
public void setCount(Count count)
{
this.count=count;
} /* methods */
public void print()
{
System.out.println(count.getCount());
}
public void run()
{
while(true)
{
if(!count.isContinue()) break;
print();
count.add();
}
}
}public class PrintB implements Runnable
{ /* methods */
public void print(Count count)
{
if(count.isContinue()) System.out.println(count.getCount());
}
public void run()
{
Count count=Count.count;
while(true)
{
if(!count.isContinue()) break;
print(count);
count.add();
}
}
}public class ThreadTest
{ public static void main(String[] args)
{
PrintA pa=new PrintA();
pa.setCount(Count.count);
PrintB pb=new PrintB();
new Thread(pa).start();
new Thread(pb).start();
}
}

解决方案 »

  1.   

    只说思路:1. 泛型
    2. 给getxxx和add加上同步即可
      

  2.   

    谢谢,
    1题我新手代码量少了,没来得及做也紧紧有点想法啊。
    不过你说的加锁我试过了。不行啊。不信你加个Thread.yield();试试纠结的处理器时间片的分布啊。它会随时离开啊。不让我一个循环玩就进入runable了哎,也就是他有可能取到了count但是还没打印出来就离开running了啊。求解
      

  3.   


    while(true)
            {
             synchronized (count) {
               // .....
                }
            }不好意思,之前没有仔细看A和B的代码。 同步的问题实际上是临界资源的问题,随便翻翻操作系统的数你就可以明白。
      

  4.   

    嗯嗯,谢谢。我主要学的web方面的。这个涉及的少。原来锁还可以这样用啊。谢谢了哈。
    还一直以为只能用在Count里面呢。