Java中没有多线程的两个线程

时间:2017-06-12 16:35:54

标签: java multithreading

我的代码:

  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

我想在这段代码中实现的是MUltithreading。 我希望thread1和thread2运行simultaniusly,你可以在输出中看到它没有以这种方式运行。

它首先运行所有撤回然后存款。 我希望撤回和存款同时以随机方式运行。 它不应该是连续运行的。 请告诉我代码中出错的地方。

2 个答案:

答案 0 :(得分:1)

I believe your code is running in parallel.

There are so few iterations in view that I don't think you would practically hit any race conditions. I suggest you put random sleeps in your code and perhaps a few locks to provoke artificial contention.

Also, consider naming your threads and connecting the jvisualvm application to inspect your running threads.

答案 1 :(得分:0)

The running sequences of threads cannot be controlled.Scheduler schedules the thread and they run.However we can put sleep sequences while thread is running.It will put thread from Running to Ready state and scheduler may schedule another thread in meantime. Thread.sleep(300)//300 is time in milliseconds

相关问题