【发布时间】:2017-06-12 16:35:54
【问题描述】:
我的代码:
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);
}
}
}
帐户.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
我想在这段代码中实现的是多线程。 我希望线程 1 和线程 2 同时运行,正如您在输出中看到的那样,它不是那样运行的。
它首先运行所有提取然后存款。 我希望取款和存款以随机方式同时运行。 它在不应该的时候连续运行。 请让我知道我的代码哪里出错了。
【问题讨论】:
-
你应该先自己调试你的代码。如果你真的想不通,你需要创建一个minimal reproducible example,这是太多的代码。同样在创建minimal reproducible example 的过程中,您通常会自己找出错误
-
它们是线程。它们独立执行,除非您以某种方式同步它们的操作。
Thread.sleep()是一种允许竞争条件的代码气味。考虑使用Executor 并按所需顺序为其提供取款和存款任务。否则,定义您想要的顺序,并使用包java.util.concurrent中的同步机制强制执行它。附带说明一下,当 Runnable 不是线程时,请不要将其命名为Thread2。 -
好的,谢谢@UnholySheep
-
感谢@AndyThomas
标签: java multithreading