thread inheritance in java

2.6k views Asked by At
   class ThreadInherit extends Helper implements Runnable 
   {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            for (int i = 1; i <= 20; i++) {
                System.out.println("Hello World");
                Thread.sleep(500);
                if (i == 10) {
                    Notify();
                    Wait();
                }                       
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

class Thread_Inherit1 extends ThreadInherit 
{
    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            Wait();
            for(int i = 1; i<=20; i++)
            {
                System.out.println("Welcome");
                Thread.sleep(550);
            }
            Notify();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block 
            e.printStackTrace();
        }
    } 
    }

    class Helper
    {
    public synchronized void Wait() throws InterruptedException
    {
        wait();
    }
    public synchronized void Notify() throws InterruptedException
    {
        notify();
    }
    }
    public class Inheritance_Class {

    public static void main (String[] args)
    {   
        Thread_Inherit1 u = new Thread_Inherit1();
        Thread_Inherit1 t = new ThreadInherit();
        t.run();
        u.run();

    }

}

So I have this code... I have a problem with this line

  Thread_Inherit1 t = new ThreadInherit();

It cannot be converted into Thread_Inherit1. Suggestions of Eclipse:

1.Add cast to Thread_Inherit1 (I did, but still giving me error) 2. Change to ThreadInherit. (probably, not the solution)

Any help?

2

There are 2 answers

8
Oleksi On

I think you really want:

 ThreadInherit t = new Thread_Inherit1();

It makes more sense to assign the subclass to have the type of the super type. The other way is probably not what you want.

Also, to start the threads, you want to call start(), not run() directly. Try this:

Thread t = new Thread(new Thread_Inherit1());
Thread u = new Thread(new ThreadInherit());

t.start();
u.start();
0
Chris M. On

Your code has:

class Thread_Inherit1 extends ThreadInherit 

... and your problem line is:

Thread_Inherit1 t = new ThreadInherit();

The trouble is that things are backwards. ThreadInherit IS NOT a thread_Inherit1. I think the line you meant to write is:

ThreadInherit t = new Thread_Inherit1();

Hopefully that'll solve your problem.