我想在Java中使用线程从给定的输入范围生成一个唯一随机数列表。例如,给定1-4的范围,我将运行4个线程,每个线程将生成一个随机数,这样就不会有两个线程两次产生相同的值。我想我需要实现一些同步什么的?我试过使用Join()
,但它似乎不起作用。
构造函数使用输入值填充给定范围的数组列表。在run方法中,我生成一个随机值(来自相同的范围)并检查它是否在列表中。如果是,我将其从列表中删除并打印该值。这个想法是,当另一个线程进入时,它不能再次生成相同的值。
到目前为止我写的是:
public class Main {
public static void main(String[] args) {
randomThreadGen randomRange = new randomThreadGen(1, 2);
Thread thread1 = new Thread(randomRange);
Thread thread2 = new Thread(randomRange);
thread1.start();
try {
thread1.join();
} catch (InterruptedException e) {
}
thread2.start();
}
}
:
public class randomThreadGen implements Runnable {
private int lowerBound;
private int upperBound;
private final ArrayList<Integer> List = new ArrayList<Integer>();
public randomThreadGen(int lowerb, int upperb) {
this.lowerBound = lowerb;
this.upperBound = upperb;
for (int i = lowerb; i < upperb + 1; i++) { // populate list with values based on lower and upperbounds specified from main
List.add(i);
}
}
@Override
public void run() {
// generate random value
// check if in list. If in list, remove it
// print value
// otherwise try again
int val = ThreadLocalRandom.current().nextInt(lowerBound, upperBound+1); // generate random value based on lower and upper bound inputs from main
while(true){
if(List.contains(val)){
List.remove(new Integer(val));
System.out.println("Random value for " + Thread.currentThread().getName() + " " + val);
System.out.println("List values: " + List);
}
break;
}
}
}'''
这个低范围的测试用例是为了使测试更容易。有时它可以工作,并且Thread0将生成与Thread01不同的值(例如1和2或2和1)。但有时它不会(似乎它们生成相同的值,在这种情况下,我的代码只打印一个值),例如,"没有别的了。
任何想法?除了join()
,还有其他方法吗?
这是一个相当简单的任务。只需使用并发哈希映射来防止重复。确保将边界声明为int,并将hashmap声明为final。线程。需要使用Join来保证在所有线程完成它们的工作后打印结果。还有其他有效的技术来代替join,但它们不适合新手。
试试这个:
import java.util.concurrent.ThreadLocalRandom;
import java.util.*;
import java.util.concurrent.*;
public class Main {
final static int low = 0;
final static int up = 5;
final static Set < Integer > inthashmap = ConcurrentHashMap.newKeySet();
// threadhashmap is needed to track down all threads generating ints
final static Set < Thread > threadhashmap = ConcurrentHashMap.newKeySet();
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < up - low + 1; i++) {
Thread t = new Thread() {
public void run() {
int randomNum;
try {
randomNum = ThreadLocalRandom.current().nextInt(low, up + 1);
inthashmap.add(randomNum);
System.out.println("A new random int generated : " + randomNum);
} finally {
}
}
};
threadhashmap.add(t);
t.start();
}
//by iterating through all threads in threadhashmap
// and joining them we guarantee that all threads were completed
// before we print the results of work of those threads (i.e. ints)
Iterator<Thread> iterator = threadhashmap.iterator();
while (iterator.hasNext())
iterator.next().join();
System.out.println("Unique ints from hashmap:");
inthashmap.forEach(System.out::println);
}
}
输出:
A new random int generated : 2
A new random int generated : 3
A new random int generated : 3
A new random int generated : 0
A new random int generated : 0
A new random int generated : 2
Unique ints from hashmap:
0
2
3