Overridden or Uses a deprecated API?

142 views Asked by At

Here is the code which I've used to calculate the factorial of a number using two threads. When I try to compile this, it says '....' uses or overrides a deprecated API, someone please help, solve this.

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();
    }
}

Also, if anyone else has a better idea to calculate factorial of a number using two threads please mention. Thanks!

2

There are 2 answers

0
Juned Ahsan On BEST ANSWER

You are getting the error because Thread.suspend is deprecated. Here is more info from the 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.

1
akash On

Here you are using suspend() which is deprecated in Java.

Try this use any boolean variable like executing to stop thread.

public void run() {
        this.executing= true;
        while (this.executing) {
            try {
                //code of factorial
            } catch (InterruptedException e) {

                this.executing= false;
            }
        }