有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多线程两个线程在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。爪哇

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。爪哇

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);
    }

}
}

账户。爪哇

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

它首先运行所有的取款和存款。 我希望取款和存款同时以随机方式运行。 它本不应该连续运行。 请让我知道我的代码哪里出错了


共 (1) 个答案

  1. # 1 楼答案

    线程的运行顺序无法控制。调度程序调度线程并运行它们。然而,我们可以在线程运行时设置睡眠序列。它将使线程从运行状态变为就绪状态,同时调度程序可能会调度另一个线程。 Thread.sleep(300)//300 is time in milliseconds