2014-04-09 55 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副本,所以將各自只有一次遞增。