同时多线程相同的代码

时间:2014-11-13 18:31:05

标签: java multithreading joptionpane biginteger

我希望我的程序能够同时测试两个BigInteger。截至目前,我的代码一次只测试一个。由于我希望两次运行的代码相同,是否有一个简单的同步语句,我可以用来实现它?

 public static void main(String[] args) {
    String input = JOptionPane.showInputDialog("Enter number ");
    int number = Integer.parseInt(input);
    BigInteger num = new BigInteger(input);

    String output = num + " is" + (IsPrime(num) ? " " : " not ")
            + "a prime number.";

    JOptionPane.showMessageDialog(null, output);
}   
public static boolean IsPrime(BigInteger num) {
    if (num.mod(new BigInteger("2")).compareTo(BigInteger.ZERO) == 0) {
      return false;
    for (BigInteger i = new BigInteger("3"); i.multiply(i).compareTo(num) <= 0; i =
        i.add(new BigInteger("2"))) {
      if (num.mod(i).compareTo(BigInteger.ZERO) == 0) {
       return false;
      }
    }
    return true;
  }
}

1 个答案:

答案 0 :(得分:0)

我已经解决了我的问题。

因为正在测试两个整数,我需要创建一个textOne和一个textTwo来单独测试每个整数。

 public static boolean IsPrime(BigInteger textOne) {
    // check if number is a multiple of 2
    if (textOne.mod(new BigInteger("2")).compareTo(BigInteger.ZERO) == 0) {
      return false;
    }// if not, then just check the odds
    for (BigInteger i = new BigInteger("3"); i.multiply(i).compareTo(textOne) <= 0; i =
        i.add(new BigInteger("2"))) {
      if (textOne.mod(i).compareTo(BigInteger.ZERO) == 0) {

       return false;
      }
    }
    return true;
}   
public static boolean IsPrime2(BigInteger textTwo) {
    // check if number is a multiple of 2
    if (textTwo.mod(new BigInteger("2")).compareTo(BigInteger.ZERO) == 0) {
      return false;
    }// if not, then just check the odds
    for (BigInteger i = new BigInteger("3"); i.multiply(i).compareTo(textTwo) <= 0; i =
        i.add(new BigInteger("2"))) {
      if (textTwo.mod(i).compareTo(BigInteger.ZERO) == 0) {

       return false;
      }
    }
    return true;
}

我指定为BigIntegers指定num和num2,以便输出反映以下内容。

public void run() {

    String output = num + " is" + (IsPrime(num) ? " " : " not ")
            + "a prime number.";
    lblResults.setText(output);

    String output2 = num2 + " is" + (IsPrime(num2) ? " " : " not ")
            + "a prime number.";
    lblResults2.setText(output2);
}}