Java中的线程继承 [英] thread inheritance in java

查看:187
本文介绍了Java中的线程继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

不能将其转换为Thread_Inherit1. Eclipse的建议:

It cannot be converted into Thread_Inherit1. Suggestions of Eclipse:

1.将演员表添加到Thread_Inherit1中(我做了,但仍然给我错误) 2.更改为ThreadInherit. (可能不是解决方案)

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

有帮助吗?

推荐答案

我认为您确实想要:

 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.

此外,要启动线程,您要直接调用start(),而不是run().试试这个:

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

这篇关于Java中的线程继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆