两个线程在 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();
            }
        */

}
}

线程1.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);
    }
}
}

线程2.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 同时运行,正如您在输出中看到的那样,它不是以这种方式运行的。

它首先运行所有提款,然后存款。我希望提款和存款以随机方式同时运行。它在不应该串行运行时运行。请让我知道我的代码哪里出错了。

我相信

你的代码是并行运行的。

鉴于迭代太少,我认为您实际上不会遇到任何竞争条件。我建议你在代码中放置随机睡眠,也许还有一些锁来引发人为的争用。

此外,请考虑命名线程并连接 jvisualvm 应用程序以检查正在运行的线程。

无法控制线程的运行顺序。调度程序调度线程并运行。但是,我们可以在线程运行时放置睡眠序列。它会将线程从"正在运行"状态置于"就绪"状态,并且调度程序可能会同时调度另一个线程。 Thread.sleep(300)//300 is time in milliseconds

最新更新