2014-04-09 49 views
0

我期待下面的增加c值为2.但即使在第二个线程启动后,我总是得到1输出。值不递增,线程

package test.main; 

public class TestThread implements Runnable { 
    private int c=0; 

    @Override 
    public void run() { 
     synchronized(this){ 
     c=c+1; 
     //wait(1000); 
     go(); 
     } 

    } 

    private void go() { 
     System.out.println("Thread name :"+Thread.currentThread()+" in go() : "+c); 
    } 

    public static void main(String[] args) throws InterruptedException { 
     System.out.println("main()"); 
     Thread t1 = new Thread(new TestThread(),"thread1"); 
     Thread t2 = new Thread(new TestThread(),"thread2"); 
     t1.start(); 
     t2.start(); 

    } 
} 

回答

1

在线程t1和t2中,您传递了两个完全不同的对象。所以在这两种情况下,它都会增加彼此不相关的c。

使用单一对象

TestThread tt = new TestThread(); 
    Thread t1 = new Thread(tt,"thread1"); 
    Thread t2 = new Thread(tt,"thread2"); 
1

您已经创建了两个线程对象。

Thread t1 = new Thread(new TestThread(),"thread1"); 
    Thread t2 = new Thread(new TestThread(),"thread2"); 

而且每个线程对象都有自己的c副本,它不是一流水平的变量。它的实例变量。

因此,它不会给你一个价值2

0
Thread t1 = new Thread(new TestThread(),"thread1"); 
Thread t2 = new Thread(new TestThread(),"thread2"); 

您正在创建TestThread的两个不同的实例和

private int c=0; 

是一个实例变量(不是类变量)。因此,对每个线程执行run()后,预计c为1。

+0

谢谢大家,大家都回答正确,但接受这个,因为这是第一个答案。我没有足够的积分为其他人+1。 – user3448119

1

每个TestThread对象都有其自己的C副本,所以将各自只有一次递增。