为了账号安全,请及时绑定邮箱和手机立即绑定

如何确定线程的执行顺序

如何确定线程的执行顺序

1996青年 2016-11-05 21:31:45
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 的顺序执行 优先级并不能稳定的确定执行顺序  有没有更好的办法
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 1182 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信