【问题标题】:threading issue with empty while loop [closed]空while循环的线程问题[关闭]
【发布时间】:2013-07-04 19:20:40
【问题描述】:

我知道如何正确执行此操作,但我想知道为什么此代码按我的意愿运行,** 没有任何注意的错误 **,而如果我删除 Thread.sleep(100); 两行while循环,程序进入死循环情况?

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.Random;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 interface Buffer
{
   // place int value into Buffer
   public void set( int value ) throws InterruptedException; 

   // obtain int value from Buffer
   public int get() throws InterruptedException; 
} // end interface Buffer


public class javaapplication32
{
   public static void main( String[] args )
   {
      // create new thread pool with two threads
      ExecutorService application = Executors.newCachedThreadPool();

      // create CircularBuffer to store ints
      CircularBuffer sharedLocation = new CircularBuffer();

      // display the initial state of the CircularBuffer
      sharedLocation.displayState( "Initial State" );

      // execute the Producer and Consumer tasks
      application.execute( new Producer( sharedLocation ) );
      application.execute( new Consumer( sharedLocation ) );

      application.shutdown();
   } // end main
}
// Consumer.java
// Consumer's run method loops ten times reading a value from buffer.


 class Consumer implements Runnable 
{ 
   private final static Random generator = new Random();
   private final Buffer sharedLocation; // reference to shared object

   // constructor
   public Consumer( Buffer shared )
   {
      sharedLocation = shared;
   } // end Consumer constructor

   // read sharedLocation's value 10 times and sum the values
   public void run()
   {
      int sum = 0;

      for ( int count = 1; count <= 10; count++ ) 
      {
         // sleep 0 to 3 seconds, read value from buffer and add to sum
         try 
         {
            Thread.sleep( generator.nextInt( 3000 ) );    
            sum += sharedLocation.get();
         } // end try
         // if lines 26 or 27 get interrupted, print stack trace
         catch ( InterruptedException exception ) 
         {
            exception.printStackTrace();
         } // end catch
      } // end for

      System.out.printf( "\n%s %d\n%s\n", 
         "Consumer read values totaling", sum, "Terminating Consumer" );
   } // end method run
} // end class Consumer

 class Producer implements Runnable 
{
   private final static Random generator = new Random();
   private final Buffer sharedLocation; // reference to shared object

   // constructor
   public Producer( Buffer shared )
   {
      sharedLocation = shared;
   } // end Producer constructor

   // store values from 1 to 10 in sharedLocation
   public void run()
   {
      int sum = 0;

      for ( int count = 1; count <= 10; count++ ) 
      {  
         try // sleep 0 to 3 seconds, then place value in Buffer
         {
            Thread.sleep( generator.nextInt( 3000 ) ); // sleep thread   
            sharedLocation.set( count ); // set value in buffer
            sum += count; // increment sum of values
         } // end try
         // if lines 25 or 26 get interrupted, print stack trace
         catch ( InterruptedException exception ) 
         {
            exception.printStackTrace();
         } // end catch
      } // end for

      System.out.println( 
         "Producer done producing\nTerminating Producer" );
   } // end method run
} // end class Producer

 class CircularBuffer implements Buffer
{
   private final int[] buffer = { -1, -1, -1 }; // shared buffer

   private int occupiedCells = 0; // count number of buffers used
   private int writeIndex = 0; // index of next element to write to
   private int readIndex = 0; // index of next element to read

   // place value into buffer
   public  void set( int value ) throws InterruptedException
   {
      // wait until buffer has space avaialble, then write value;
      // while no empty locations, place thread in waiting state
      while (  occupiedCells == buffer.length) 
      {
        Thread.sleep(100);
      } // end while

      buffer[ writeIndex ] = value; // set new buffer value

      // update circular write index
      writeIndex = ( writeIndex + 1 ) % buffer.length;

      ++occupiedCells; // one more buffer cell is full
      displayState( "Producer writes " + value );
     // notifyAll(); // notify threads waiting to read from buffer
   } // end method set

   // return value from buffer
   public  int get() throws InterruptedException
   {
      // wait until buffer has data, then read value;
      // while no data to read, place thread in waiting state
      while (occupiedCells == 0 ) 
      { 
      **Thread.sleep(100);**
      } // end while

      int readValue = buffer[ readIndex ]; // read value from buffer

      // update circular read index
      readIndex = ( readIndex + 1 ) % buffer.length;

      --occupiedCells; // one fewer buffer cells are occupied
      displayState( "Consumer reads " + readValue );
   //   notifyAll(); // notify threads waiting to write to buffer

      return readValue;
   } // end method get

   // display current operation and buffer state
   public void displayState( String operation )
   {
      // output operation and number of occupied buffer cells
      System.out.printf( "%s%s%d)\n%s", operation, 
         " (buffer cells occupied: ", occupiedCells, "buffer cells:  " );

      for ( int value : buffer )
         System.out.printf( " %2d  ", value ); // output values in buffer

      System.out.print( "\n               " );

      for ( int i = 0; i < buffer.length; i++ )
         System.out.print( "---- " );

      System.out.print( "\n               " );

      for ( int i = 0; i < buffer.length; i++ )
      {
         if ( i == writeIndex && i == readIndex )
            System.out.print( " WR" ); // both write and read index
         else if ( i == writeIndex )
            System.out.print( " W   " ); // just write index
         else if ( i == readIndex )
            System.out.print( "  R  " ); // just read index
         else
            System.out.print( "     " ); // neither index
      } // end for

      System.out.println( "\n" );
   } // end method displayState
}

我的问题不是如何正确地做到这一点,而是

  • 如果我在上面运行此代码,我会得到我想要的,尝试一下就知道它是如何工作的
  • 但如果我从两个 while 循环中删除 Thread.sleep(100); ,则代码不会在我使用 Thread.sleep(100); 运行时运行在前一种情况下。

【问题讨论】:

  • 无论哪种方式,您的代码都处于有限循环中,只是处理器每秒只检查条件十次,而不是在不睡觉的情况下尝试数千次。
  • 你选择的方法很糟糕,很糟糕!为什么你会一次又一次地检查a变量,你需要synchronize线程彼此
  • 为什么要投反对票?让他学习...+1 好问题
  • @MarvinEmilBrach 好点,我会像你 +1 那样做,对于 Java

标签: java multithreading


【解决方案1】:

Thread.sleeps 用于减少不必要的 CPU 使用。在不休眠的单核系统上,可能会占用其他线程的 CPU 时间,因此可能需要很长时间才能摆脱自旋锁。无论如何,look into using wait() and notify() 而不是实现自己的自旋锁。

【讨论】:

【解决方案2】:

我不相信它是无限的,但它会朝着这个方向发展。查看已使用的处理器容量。只要两个线程在同一个进程中运行,就共享同一个处理器内核。我敢打赌,检查将获得所有资源...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-21
    • 2020-06-03
    • 2014-08-03
    • 2011-06-19
    • 1970-01-01
    相关资源
    最近更新 更多