2017-06-12 71 views
0

我的代碼:兩個線程不是多線程Java中

Test.java 

    public class Test { 

    public static void main(String[] args) { 

    Account acc = new Account(); 

    Thread1 t1 = new Thread1(acc); 
    Thread2 t2 = new Thread2(acc); 
    Thread t = new Thread(t2); 


    t1.start(); 
    t.start(); 



     /* 
     for(int i=0;i<10;i++){ 
      System.out.println("Main Thread : "+i); 
      try { 
       Thread.sleep(100); 
      } catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     */ 


} 

} 

Thread1.java

public class Thread1 extends Thread { 

Account acc; 

public Thread1(Account acc){ 
    super(); 
    this.acc=acc; 
} 

@Override 
public void run() { 

    for(int i=0;i<10;i++){ 
     acc.withdraw(100); 
    } 

} 

} 

Thread2.java

public class Thread2 implements Runnable { 

Account acc; 

public Thread2(Account acc){ 
    super(); 
    this.acc=acc; 
} 

public void run() { 

    for(int i=0;i<10;i++){ 
     acc.deposit(100); 
    } 

} 
} 

Account.java

public class Account { 

volatile int balance = 500; 

public synchronized void withdraw(int amount){ 
    try { 
     if(balance<=0){ 
      wait(); 
     } 

     balance=balance-amount; 
     Thread.sleep(100); 
     System.out.println("Withdraw : "+balance); 

    } catch (InterruptedException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

public synchronized void deposit(int amount){ 
    try { 
     balance = balance+amount; 
     Thread.sleep(100); 
     System.out.println("Deposit : "+balance); 

     notify(); 
    } catch (InterruptedException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

} 

OUTPUT: 
Withdraw : 400 
Withdraw : 300 
Withdraw : 200 
Withdraw : 100 
Withdraw : 0 
Deposit : 100 
Deposit : 200 
Deposit : 300 
Deposit : 400 
Deposit : 500 

我想在這段代碼中實現的是多線程。 我希望thread1和thread2運行simultaniusly,因爲您可以在輸出中看到它不會以這種方式運行。

它首先運行所有提款然後存款。 我想同時以隨機方式退出和存款。 當它不應該是連續運行時。 請讓我知道我的代碼出錯了。

+2

你應該先自己調試你的代碼。如果你真的搞不清楚,你需要創建一個[mcve],這是太多的代碼。同樣在創建[mcve]的過程中,您經常會自己弄清楚自己的錯誤 – UnholySheep

+0

它們是線程。除非你以某種方式同步他們的行爲,否則他們會獨立執行。 'Thread.sleep()'是一種允許競爭條件的代碼氣味。考慮使用[Executor](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html)並以期望的順序爲其提取和存入任務。否則,請定義您想要的順序,並使用'java.util.concurrent'包中的同步機制強制執行它。作爲一個方面說明,當它不是一個線程時,考慮不要誤導性地將Runnable命名爲'Thread2'。 –

+0

好的謝謝@UnholySheep – Fusionist

回答

1

我相信你的代碼是並行運行的。

有很少的迭代,我認爲你幾乎不會遇到任何競爭條件。我建議你在你的代碼中放置隨機的睡眠,並且可能有一些鎖會引起人爲爭奪。

另外,考慮命名您的線程並連接jvisualvm應用程序來檢查您正在運行的線程。

+0

非常感謝@Sam – Fusionist

0

線程的運行順序不能controlled.Scheduler調度線程和他們run.However我們可以把睡眠序列,而線程running.It會把線程運行準備狀態和調度可調度的同時另一個線程。 Thread.sleep(300)//300 is time in milliseconds

+0

OP的代碼已經在使用'Thread.sleep()'。使用'Thread.sleep()'通常是一種代碼異味,因爲它不能保證多個獨立線程之間的任何執行順序。 –