有没有办法在没有Syncronized的情况下使用wait()或interrupt()?

时间:2015-09-19 02:05:21

标签: java multithreading wait

假设我有一个线程正在运行,我想让它等待然后被中断,以便它将再次运行。但是,对于我的作业,我不允许对我的方法使用Synchronized标记。有没有其他方法可以使用wait()或可能使用其他内置方法来执行我想要的操作?还是比这更复杂? 谢谢!

 public void run()
   {     
     int counter = 0;
     Thread t = new Thread();

     while(counter < 1){
     sleepTime = generator.nextInt((3000-200)+1)+200;
     withdrawAmount = generator.nextInt(50-1+1)+1;
     balance = BalanceCall.getBalance();
     if ((balance - withdrawAmount) > 0){
     t.interrupt();

     balance = BalanceCall.updateBalance(withdrawAmount, "Withdraw");
     System.out.print("         " + threadName + " withdraws $" + withdrawAmount + "        Balance is $" + balance + "\n");
     }

     else{
        System.out.print("          " + threadName + " withdraws $" + withdrawAmount + " Withdrawal - Blocked - Insufficient Funds\n");
        try {
            Thread.sleep(100000);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
     }

     try {
         Thread.sleep(sleepTime);
     } 

     catch (InterruptedException e) {
         e.printStackTrace();
     }
     }
   } // end method run

1 个答案:

答案 0 :(得分:0)

您可以使用Long.MAX_VALUE。 Thread.sleep方法睡眠给定的毫秒数。 Thread.interrupt()毫秒几乎是无限的(数亿年)。但是,.js会中断睡眠。