package com.oracle.thread;
import java.util.concurrent.CountDownLatch;
public class PrimeNumber implements Runnable{
int num;
static int sum = 0;
public PrimeNumber(int num) {
this.num=num;
}
final Integer mutex = 1;
CountDownLatch latch = new CountDownLatch(3) ;
@Override
public void run() {
try {
synchronized (mutex) {
int i = num-1000+1;
while(i<num){
if(isPrime(i)){
System.out.println(Thread.currentThread().getName()+":"+i);
sum++;
}
i++;
}
}
} catch (Exception e) {
}finally {
latch.countDown();
System.out.println(sum);
}
}
public static boolean isPrime(int n){
for(int i = 2;i<n ;i++){
if(n%i==0)
return false;
}
return true;
}
public static void main(String[] args) {
PrimeNumber p1 = new PrimeNumber(1000);
PrimeNumber p2 = new PrimeNumber(2000);
PrimeNumber p3 = new PrimeNumber(3000);
Thread t1 = new Thread(p1,"线程1");
t1.setPriority(Thread.MAX_PRIORITY);
Thread t2 = new Thread(p2,"线程2");
t2.setPriority(Thread.NORM_PRIORITY);
Thread t3 = new Thread(p3,"线程3");
t3.setPriority(Thread.MIN_PRIORITY);
t1.start();
t2.start();
t3.start();
}
}
我想让线程稳定的按照t1 t2 t3 的顺序执行 优先级并不能稳定的确定执行顺序 有没有更好的办法
相关分类