Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 空while循环的线程问题_Java_Multithreading - Fatal编程技术网

Java 空while循环的线程问题

Java 空while循环的线程问题,java,multithreading,Java,Multithreading,我知道如何正确地执行该操作,但我想知道为什么这段代码会像我希望的那样运行,**没有任何错误**,而如果我删除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.Rand

我知道如何正确地执行该操作,但我想知道为什么这段代码会像我希望的那样运行,**没有任何错误**,而如果我删除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
}
import java.util.Random;
导入java.util.concurrent.ExecutorService;
导入java.util.concurrent.Executors;
导入java.util.Random;
导入java.util.Random;
导入java.util.concurrent.ExecutorService;
导入java.util.concurrent.Executors;
接口缓冲区
{
//将int值放入缓冲区
公共无效集(int值)抛出InterruptedException;
//从缓冲区获取int值
public int get()抛出InterruptedException;
}//结束接口缓冲区
公共类javaapplication32
{
公共静态void main(字符串[]args)
{
//创建包含两个线程的新线程池
ExecutorService应用程序=Executors.newCachedThreadPool();
//创建CircularBuffer以存储整数
CircularBuffer sharedLocation=新的CircularBuffer();
//显示循环缓冲区的初始状态
sharedLocation.displayState(“初始状态”);
//执行生产者和消费者任务
应用程序。执行(新生产者(共享位置));
application.execute(新消费者(共享位置));
application.shutdown();
}//末端总管
}
//Consumer.java
//使用者的run方法循环十次,从缓冲区读取值。
类使用者实现Runnable
{ 
专用最终静态随机生成器=新随机();
私有最终缓冲区sharedLocation;//对共享对象的引用
//建造师
公共使用者(缓冲区共享)
{
sharedLocation=共享;
}//最终使用者构造函数
//读取sharedLocation的值10次,然后求和
公开募捐
{
整数和=0;

对于(int count=1;count线程。睡眠可以减少不必要的CPU使用。在单核系统上,不睡眠可能会耗尽其他线程的CPU时间,因此可能需要很长时间才能摆脱自旋锁。在任何情况下,与其实现自己的自旋锁,不如实现自己的自旋锁。

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

无论哪种方式,您的代码都是在有限循环中,只是处理器每秒只检查十次条件,而不是多次一千次不睡觉的尝试。不相关,但仍然-你选择的方法非常糟糕,太糟糕了!为什么你要一次又一次地检查a变量,你需要彼此线程为什么向下投票?让他学习…+1很好question@MarvinEmilBrach说得好,我会像你做的那样做+1,因为Java+1你打败了我n时间和质量:DAlso可以建议使用并发包:@Jyro117在某种程度上看起来已经是了。:)我的意思是锁:P