采用线程实现“生产者-消费者”编程的基础模型
源代码
消费者代码:
public class Consumer implements Runnable {
BlockingQueue< Integer> blockingQueue;
int n;
CountDownLatch countDownLatch;
public Consumer ( BlockingQueue< Integer> blockingQueue, int n, CountDownLatch countDownLatch) {
this . blockingQueue = blockingQueue;
this . n = n;
this . countDownLatch= countDownLatch;
}
@Override
public void run ( ) {
for ( int i= 0 ; i< n; i++ )
{
try {
int cur= blockingQueue. take ( ) ;
isPrime ( cur) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
System. out. println ( "消费者完成" ) ;
countDownLatch. countDown ( ) ;
}
int isPrime ( int n)
{
double n_sqrt;
if ( n== 2 || n== 3 ) return 1 ;
if ( n% 6 != 1 && n% 6 != 5 ) return 0 ;
n_sqrt= Math. floor ( Math. sqrt ( ( float ) n) ) ;
for ( int i= 5 ; i<= n_sqrt; i+= 6 )
{
if ( n% ( i) == 0 | n% ( i+ 2 ) == 0 ) return 0 ;
}
return 1 ;
}
}
生产者代码:
public class Producer implements Runnable {
BlockingQueue< Integer> blockingQueue;
int n;
CountDownLatch countDownLatch;
public Producer ( BlockingQueue< Integer> blockingQueue, int n, CountDownLatch countDownLatch) {
this . blockingQueue = blockingQueue;
this . n = n;
this . countDownLatch= countDownLatch;
}
@Override
public void run ( ) {
Random ra = new Random ( ) ;
for ( int i= 0 ; i< n; i++ )
{
try {
blockingQueue. put ( ra. nextInt ( 2000000000 ) + 1 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
System. out. println ( "生产者完成" ) ;
countDownLatch. countDown ( ) ;
}
}
主类:
public class Model {
public static void excute ( int producerNum, int consumerNum, int num, CountDownLatch countDownLatch)
{
BlockingQueue< Integer> blockingQueue= new LinkedBlockingQueue < > ( num) ;
for ( int i= 0 ; i< producerNum; i++ )
{
new Thread ( new Producer ( blockingQueue, num/ producerNum, countDownLatch) ) . start ( ) ;
}
for ( int i= 0 ; i< consumerNum; i++ )
{
new Thread ( new Consumer ( blockingQueue, num/ consumerNum, countDownLatch) ) . start ( ) ;
}
}
public static void main ( String[ ] args) {
CountDownLatch countDownLatch= new CountDownLatch ( 6 ) ;
long s= System. currentTimeMillis ( ) ;
excute ( 2 , 4 , 1000000 , countDownLatch) ;
try {
countDownLatch. await ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
System. out. println ( ( double ) ( System. currentTimeMillis ( ) - s) / 1000 ) ;
}
}