由于我是多线程新手,因此无法实现以下方案。任何人都可以帮我这个吗?
要求如下:
一个线程创建了从1到无穷大的素数。另一个将这些数字写入控制台的线程。编写运行这两个线程的代码。
这就是我的尝试:
class func1 implements Runnable{
public void run(){
int x=1, counter=0;
for (int i=0; i<=infinity; i++){
if (isPrime(i)){
p[counter] = i;
counter++;
}
}
}
}
class func2 implements Runnable{
public void run(){
int x=1, counter=0;
int[] p=0;
for (int i=0; i<=infinity; i++){
System.out.println(“Prime number:”+p[i]);
}
}
}
public class test{
static volatile int[] arr;
public static void main(String[] args){
func1 obj1 = new func1(arr);
func2 obj2 = new func2(arr);
thread t1, t2;
t1 = new thread(obj1);
t2 = new thread(obj2);
t1.start();
t2.start();
}
答案 0 :(得分:1)
以下是生产者消费者模式的简单示例。生产者创建一些整数值,在阻塞队列中填充它们,消费者从队列中提取它们。
制片:
import java.util.concurrent.BlockingQueue;
public class Producer implements Runnable{
BlockingQueue<Integer> queue;
public Producer(BlockingQueue<Integer> queue){
this.queue = queue;
}
@Override
public void run() {
for(int i=0;i<10;i++){
queue.offer(i);
}
}
}
消费者:
import java.util.concurrent.BlockingQueue;
public class Consumer implements Runnable {
BlockingQueue<Integer> queue;
public Consumer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
while (true) {
if (queue.peek() != null) {
Integer number = queue.poll();
System.out.println("Integer is >>> " + number);
}
}
}
}
测试类:
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class Main {
public static void main(String args[]) {
BlockingQueue queue = new ArrayBlockingQueue(10);
Producer producer = new Producer(queue);
Consumer consumer = new Consumer(queue);
Thread producerThread = new Thread(producer);
Thread consumerThread = new Thread(consumer);
producerThread.start();
consumerThread.start();
}
}
您可以生产/消费素数。 Producer / Consumer的run()方法内部的逻辑将发生变化。这也可以使用wait / notify实现。