【发布时间】:2020-07-25 19:28:56
【问题描述】:
我是多线程新手。所以这是我正在处理的问题:将学生证的最后四位数字存储在两个单独的班级中。例如,如果您的 ID 是 SE123456789,则将 67 存储在第一个 Thread1 类中,将 89 存储在 Thread2 类中,稍后将传递给 Factorial 类。
Thread1 类将 67 传递给 Factorial 类,printfactorial() 将打印从 1 到 67 的所有数字的阶乘。
Thread2 类将 89 传递给 Factorial 类,printfactorial() 将打印从 1 到 89 的所有数字的阶乘。
您应该在循环内的每次计算后使用 thread.sleep(10)。
如您所知,您不能在简单的整数或长类型变量中存储和打印大数的阶乘,因此您需要使用 BigInteger 来存储和打印非常长的数字。
printfactorial() 方法必须同步,以便首先打印 Thread1 的结果,然后计算并打印 Thread2 的结果。
这就是我到目前为止所做的。
我有四个不同的班级
Main
Factorial
Thread1
Thread2
Thread1 和 Thread2 都扩展了 Thread 类。 这是我目前写的代码:
主要
public class Main {
public static void main(String args[]){
Factorial factorial = new Factorial();
Thread1 t1 = new Thread1(factorial);
Thread1 t2 = new Thread1(factorial);
t1.start();
t2.start();
}
}
阶乘类
import java.math.BigInteger;
public class Factorial {
public void printFactorial(int number){
BigInteger bigInteger = new BigInteger("1");
try{
for(int i=1; i<=number; i++){
bigInteger = bigInteger.multiply(BigInteger.valueOf(i));
Thread.sleep(10);
System.out.println(bigInteger);
}
}catch(InterruptedException ex){
System.out.println("the interruption has occurred in the thread");
}
}
}
线程1
package com.mycompany.factorial;
public class Thread1 extends Thread {
Factorial factorial;
Thread1(Factorial fact){
factorial = fact;
}
@Override
public void start(){
synchronized(factorial){
try{
/*my ID is: SE170400080
so the second last two digits are 00.
**/
factorial.printFactorial(00); //here's the problem
}catch(Exception e){
System.out.println("the interruption has occurred in the thread");
}
}
}
}
线程2
package com.mycompany.factorial;
public class Thread2 extends Thread {
Factorial factorial;
Thread2(Factorial fact){
factorial = fact;
}
@Override
public void start(){
synchronized(factorial){
try{
factorial.printFactorial(80);
}catch(Exception e){
System.out.println("the interruption has occurred in the thread");
}
}
}
}
运行主程序后,它成功构建但不显示所需的输出。
非常感谢您的帮助,我已尽力保持重点。
1:
【问题讨论】:
-
您确定您正在运行该项目而不仅仅是构建它吗?顺便说一句,您不需要同步对
Factorial.printFactorial方法的访问,因为它不操作共享数据。 -
@AndrewVershinin 是的,我构建它而不是运行它。
-
不要覆盖
start()。如果你这样做,那么t1.start()和t2.start()调用只是调用你自己的代码,并且不会创建任何线程。改写Thread.run()方法。 -
你说,“......我构建然后运行它。”是什么让你认为你正在运行它?为什么不在
main(...)一开始就在它做任何其他事情之前添加一个println("I am alive!")语句?如果你没有看到“我还活着!”打印在控制台输出中,那么询问为什么没有打印其他内容是没有意义的。 -
Re, "...printFactorial(00); // 这就是问题所在" 这是作业的问题——你的导师显然没有考虑过这种情况——但我不认为这是您的代码有问题。您的 printFactorial 方法应该打印从 1 到 N 的所有数字的阶乘。嗯,没有从 1 到 0 的任何数字,所以如果
printFactorial(0)不打印任何东西,那么它就完全按照作业所说的去做了。
标签: java multithreading