有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java被覆盖或使用不推荐的API?

这是我使用两个线程计算数字阶乘的代码。 当我试图编译它时,它会说“…”使用或覆盖不推荐的API,请有人帮助解决此问题

import java.lang.Thread;
import java.util.Scanner;

class A extends Thread
{
    int n;
    int fact=1;
    int i;
    A(int x)
    {
        n=x;
        i=n;
    }
    public void run()
    {
        if(i>0)
        {
            fact=fact*i;
            i--;
        }
        else
            System.out.print(fact);
            suspend();
    }
}

class B extends Thread
{
    int i;
    int n;
    int fact=1;
    B(int x)
    {
        n=x;
        i=n;
    }
    public void run()
    {
        if(i>0)
        {
            fact=fact*i;
            i--;
        }
        else
            System.out.print(fact);
            suspend();
    }
}

class refact
{
    public static void main(String args[])
    {
        int n;
        System.out.print("Enter the number you want :");
        Scanner a = new Scanner(System.in);
        n=a.nextInt();
        System.out.print("\n\n");
        A newthreadA = new A(n);
        newthreadA.start();
        B newthreadB = new B(n);
        newthreadB.start();
    }
}

另外,如果其他人有更好的想法,使用两个线程计算一个数字的阶乘,请提及。 谢谢


共 (2) 个答案

  1. # 1 楼答案

    这里使用的是suspend(),Java中不推荐使用它

    尝试使用任何布尔变量,如executing来停止线程

    public void run() {
            this.executing= true;
            while (this.executing) {
                try {
                    //code of factorial
                } catch (InterruptedException e) {
    
                    this.executing= false;
                }
            }
    
  2. # 2 楼答案

    您得到的错误是因为线程。suspend已被弃用。以下是来自docs的更多信息:

    Why are Thread.suspend and Thread.resume deprecated?

    Thread.suspend is inherently deadlock-prone. If the target thread holds a lock on the monitor protecting a critical system resource when it is suspended, no thread can access this resource until the target thread is resumed. If the thread that would resume the target thread attempts to lock this monitor prior to calling resume, deadlock results. Such deadlocks typically manifest themselves as "frozen" processes.