我使用100个线程求sum+1的和100次。使用了synchronized为什么还是不能正确求和呢,每次不都是只有一个线程能运行run()吗。结果应该是100。但打印出来的有99,77等,每次都不一样。
package Thread;class newRunnable implements Runnable{
private int sum =0;
public synchronized void run(){
sum+=1;
Thread.yield();
}
public void print(){
System.out.println(sum);
}
}public class MyRunnable{
public static void main(String[] args){
newRunnable x = new newRunnable();
for(int i=0;i<2;++i){
new Thread(x).start();
}
x.print();
}
}

解决方案 »

  1.   

    for(int i=0;i<2;++i){
                new Thread(x).start();
            }
            x.print();这样不能保证主线程在所有子线程执行完后才打印吧
      

  2.   

    主线程不会等其它的线程都执行了才继续执行Thread t = new Thread(x);
    t.start();
    try {
    t.join();
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    可以阻止其他的线程访问run方法,但不能阻止它访问其它的方法(print)
    class newRunnable implements Runnable{
    private int sum =0;
    public  void run(){
    synchronized(this)
    {
    sum=sum+1;
    }
    }
    public void print(){
    System.out.println("1--->"+sum);
    }
    }public class MyRunnable{
    public static void main(String[] args){
    newRunnable x = new newRunnable();
    for(int i=0;i<100;i++){
     new Thread(x).start();
    }
    x.print();
    }
    }
      

  3.   

    我有点明白了,是主进程和线程运行顺序的问题,不过代码感觉还是写不好,能帮我写出来吗?我想用Runnable实现,使用t.join()这个我只能建立一个线程吧,那要是想建立多个线程该怎么办呀?
    看看下面的程序可以吗?
    class newRunnable implements Runnable{
        private int sum =0;
        public  void run(){
            synchronized(this)
            {
                sum=sum+1;
            }
        }
        public void print(){
            System.out.println("1--->"+sum);
        }
    }public class MyRunnable{
        public static void main(String[] args){
            newRunnable x = new newRunnable();
            Thread t = null;
            for(int i=0;i<100;i++){
                 t = new Thread(x);
                 t.start();
                 try{
                  t.join();
                 }catch(InterruptedException e){
                  System.out.println(e.getMessage());
                 }
            }
            x.print();
        }
    }
      

  4.   

    1
    private int sum =0;要变成static的
    private static int sum =0;从而所有线程共享变量
    2要等所有线程运行完成以后再打印结果x.print();
      

  5.   

    3你创建的是一个线程对象newRunnable ,它只会运行一次
      

  6.   

    class newRunnable implements Runnable{
    private int sum = 0; 
        public void run(){
         sum++;
        }
        public void print(){
            System.out.println(sum);
        }
    }public class MyRunnable{
        public static void main(String[] args){
            newRunnable x = new newRunnable();
            for(int i=0;i<100;i++){
                new Thread(x).start();
            }
            while (Thread.activeCount()>1){}        
            x.print();
        }
    }