我的代碼:兩個線程不是多線程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,因爲您可以在輸出中看到它不會以這種方式運行。
它首先運行所有提款然後存款。 我想同時以隨機方式退出和存款。 當它不應該是連續運行時。 請讓我知道我的代碼出錯了。
你應該先自己調試你的代碼。如果你真的搞不清楚,你需要創建一個[mcve],這是太多的代碼。同樣在創建[mcve]的過程中,您經常會自己弄清楚自己的錯誤 – UnholySheep
它們是線程。除非你以某種方式同步他們的行爲,否則他們會獨立執行。 'Thread.sleep()'是一種允許競爭條件的代碼氣味。考慮使用[Executor](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html)並以期望的順序爲其提取和存入任務。否則,請定義您想要的順序,並使用'java.util.concurrent'包中的同步機制強制執行它。作爲一個方面說明,當它不是一個線程時,考慮不要誤導性地將Runnable命名爲'Thread2'。 –
好的謝謝@UnholySheep – Fusionist