[英]Generating infinite sequence of numbers using 7 threads
我正在尝试使用 Java 中的不同线程生成无限的数字序列。 这是我的代码:
import java.util.*;
public class infinite_Streams {
volatile boolean keepGenerating = true;
volatile ArrayList<Integer> s1 = new ArrayList<>();
Object lock1 = new Object();
Random random = new Random();
ArrayList<Object> obj1 = new ArrayList<>();
void generateInfiniteStream() {
synchronized (lock1) {
//BLOCK 1
while(keepGenerating) {
Object temp = Thread.currentThread().getId();
System.out.println("Thread is : " + temp);
s1.add(random.nextInt(11));
}
}
//BLOCK 1 ENDS
//BLOCK 2
// for (int i = 0; i < 100000; i++) {
// Object temp = Thread.currentThread().getId();
// System.out.println("Thread is : " + temp);
// s1.add(random.nextInt(11));
// }
//BLOCK 2 ENDS
}
void generateThreads(int num_threads){
Thread[] threads = new Thread[num_threads];
for(int i = 0 ; i < num_threads ; i++){
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
generateInfiniteStream();
}
});
}
for (Thread thread : threads) {
thread.start();
}
try{
for (Thread thread : threads) {
thread.join();
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
public void shutdown(){
keepGenerating = false;
}
public static void main(String [] args){
List<Integer> l1 = new ArrayList<>();
int num_threads = 7;
Scanner scan1 = new Scanner(System.in);
infinite_Streams is1 = new infinite_Streams();
is1.generateThreads(num_threads);
System.out.println("Press any key to interrupt");
Scanner scan2 = new Scanner(System.in);
scan2.nextLine();
is1.shutdown();
}
}
代码似乎确实生成了我需要的东西。 但我也有兴趣了解如何涉及不同的线程。要查看我打印的内容(可以在\\\\BLOCK1
看到)
Object temp = Thread.currentThread().getId();
System.out.println("Thread is : " + temp);
问题是我只看到一个特定的线程,比如12
,所以输出看起来像Thread is : 12
always 。 另一方面,如果我注释\\\\BLOCK1
代码,而是运行\\\\BLOCK2
代码,它生成有限数量的数字,我会在输出中看到不同的线程编号,正如预期的那样。 就像Thread is : 12
Thread is : 12
Thread is : 14
等等。有人可以解释一下,为什么我在生成无限数时没有看到不同的线程数?
线程之一获得锁。 然后它会执行while(keepGenerating)直到您更改此变量。 所有其他线程都在等待,直到锁空闲。 当您将keepGenerating设置为false 时,正在运行的线程将完成循环。 其他线程之一获得锁。 但是此时keepGenerating已经为false,所以不执行这个循环,直接退出。 然后下一个线程获得锁并再次看到没有什么可做的。 等等。
所以实际上只有一个线程在生成随机数。
如果你希望每个线程都生成随机数,你应该在同步块之外使用while(keepGenerating) ,而不是在它之外,如下所示:
while(keepGenerating) {
synchronized (lock1) {
Object temp = Thread.currentThread().getId();
System.out.println("Thread is : " + temp);
s1.add(random.nextInt(11));
}
}
然后每个线程将不会永远获得锁定,而只是为了数字生成和输出的单次执行。 然后锁将被释放,其他线程可以得到它,等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.