我的代码:两个线程不是多线程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