【发布时间】:2018-04-10 17:14:13
【问题描述】:
我正在尝试打印一个点到另一个点之间的素数,比如说在一个线程中从 1 到 1000,在另一个线程中从 1000 到 2000,但是当我使用 foreach 循环打印每个线程时,它会给我一个无序的 Arraylist 打印出来两次。
我正在尝试使用两个并发线程打印 1、2、3、5、7...。请帮助我,以便我更好地理解线程。
public class PrimeNumberGenerator implements Runnable{
protected long from, to;
static ArrayList<Long> primeList = new ArrayList<Long>();
public PrimeNumberGenerator(long from,long to)
{
this.from = from;
this.to = to;
}
public long count = 0;
public void run() {
for(long n=from; n<=to; n++){
boolean isPrime = true;
for(long i = 2; i<n; i++) {
if(n % i==0) {
isPrime = false;
break;
}
}
if(isPrime) {
count++;
primeList.add(n);
}
}
}
public ArrayList<Long> getPrimes() {
return primeList;
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
PrimeNumberGenerator gen1 = new PrimeNumberGenerator(1L,1000L);
PrimeNumberGenerator gen2 = new PrimeNumberGenerator(1001L,2000L);
Thread t1 = new Thread(gen1);
Thread t2 = new Thread(gen2);
t1.start();
t2.start();
t1.join();
t2.join();
gen1.getPrimes().forEach(primeList -> System.out.println(primeList));
gen2.getPrimes().forEach(primeList -> System.out.println(primeList));
}
}
【问题讨论】:
-
你在两个循环中调用 system out printline。
-
由于 ArrayList 是静态的,因此两个线程都在添加。当您调用 System.out.println 时,您将打印同一个线程两次。如果顺序很重要,我建议使用 TreeSet,它将被订购。
-
不会使用每个对象打印每个线程然后再打印第二个吗?
-
@JainamShah 由于列表是静态的,因此两个线程都使用它的相同实例。
-
此外,它们以非线程安全的方式访问同一个实例。你很幸运,没有看到异常或数据损坏。
标签: java multithreading