Java 同时多线程处理相同的代码
我想让我的程序同时测试两个Java 同时多线程处理相同的代码,java,multithreading,joptionpane,biginteger,Java,Multithreading,Joptionpane,Biginteger,我想让我的程序同时测试两个bigingers。到目前为止,我的代码正在一次测试一个。因为我希望两次运行的代码都相同,所以有没有一个简单的synchronized语句可以用来实现这一点 public static void main(String[] args) { String input = JOptionPane.showInputDialog("Enter number "); int number = Integer.parseInt(input); BigIn
biginger
s。到目前为止,我的代码正在一次测试一个。因为我希望两次运行的代码都相同,所以有没有一个简单的synchronized语句可以用来实现这一点
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;
}
}
publicstaticvoidmain(字符串[]args){
字符串输入=JOptionPane.showInputDialog(“输入数字”);
int number=Integer.parseInt(输入);
BigInteger num=新的BigInteger(输入);
字符串输出=num+“是”+(IsPrime(num)?“”:“不是”)
+“质数。”;
showMessageDialog(null,输出);
}
公共静态布尔值IsPrime(BigInteger num){
if(num.mod(新的BigInteger(“2”)).compareTo(BigInteger.ZERO)==0){
返回false;
对于(biginger i=new biginger(“3”);i.multiply(i).compareTo(num)我已经找到了问题的解决方案
因为要测试两个整数,所以我需要创建一个textOne和一个textwo来分别测试每个整数的素数
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;
}
你的目标是对两种算法进行基准测试,还是仅仅使用n个并行线程来处理某件事情?@Robert using parallel@Maticiero那么你之前的评论是什么意思:)?或者你为什么还要费心搜索个人资料图像……堆栈溢出不是社交网络。我们试图关注问题,而不是人。(顺便说一句,无论谁对OP的所有帖子进行了投票,连续投票都是毫无意义的,这样的投票将在以后被删除,在OP档案中留下大量的-amount
)因此,您可以从传递的Callable
为每个调用IsPrime
的BigInteger创建并启动一个新的线程
实例,但您想为每个实例创建一个对话框吗?@Maticiero您是谁?
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);
}}