各位大大 synchronized(object o){}可以保护单CPU运行多线程时的公共代码段 但是多CPU的时候好象就不行了 那么多CPU的情况下这个方法还能用吗 

解决方案 »

  1.   

    多CUP怎么就不行了呢?你测试过 ?
      

  2.   

    以下是我的代码 如果是单CPU 最终结果到1就终止了 但是如果是多CPU 最终结果就到-2才终止
    class MyThreadTest
    {
    public static void main(String[] args){
    ThreadTest tt = new ThreadTest();
    new Thread(tt).start();
    new Thread(tt).start();
    new Thread(tt).start();
    new Thread(tt).start();
    }
    }class ThreadTest implements Runnable
    {
    int i = 100;
    Object o = new Object();
    public void run(){
    while(i>0){
    synchronized(o){
    try{
    Thread.sleep(10);
    System.out.println("出来吧~~"+Thread.currentThread().getName()+"      "+i);
    i--;
    }catch(Exception e){
    e.printStackTrace();
    }
    }
    }
    }
    }
      

  3.   

    是你的同步区块有问题:while (i > 0) {// <<<-----这里while(i>0)不在同步区块,因此在底下同步区块阴塞时,代码还是能进入这个循环,把 synchronized (o)提到while前就可以了
    synchronized (o) {
    try {
    Thread.sleep(10);
    System.out.println("出来吧~~" + Thread.currentThread().getName() + " " + i);
    i--;
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }
      

  4.   

    public static void main(String[] args){
    ThreadTest tt = new ThreadTest();
    new Thread(tt).start();
    new Thread(tt).start();
    new Thread(tt).start();
    new Thread(tt).start();这个地方我把后面三个new Thread(tt).start();删掉 结果是到1截止
      

  5.   

    因为同步放外面后,你睡眠并没有释放锁,只有同步块内的代码运行完别的线程才可以得到锁。见下面代码:public void run() {
    synchronized (o) {
    if (0 == i) {
    System.out.println("出来吧~~" + Thread.currentThread().getName() + " " + i);
    }
    while (i > 0) { try {
    Thread.sleep(10);
    System.out.println("出来吧~~" + Thread.currentThread().getName() + " " + i);
    i--;
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }
    }