如何将下面的示例转换为实现Runnable接口并覆盖run方法

时间:2016-10-07 06:11:21

标签: java multithreading inheritance

我有2个简单的类,比如bellow。但是,我想在类声明中实现runnable接口,而不是在Thread对象声明中使用它。但是,我没有喘息如何将其转换为以上格式。

public class Main{

    static Runner r1 =new Runner();
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Thread t1 = new Thread (new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    r1.firstThread();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });

        Thread t2 = new Thread (new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    r1.secondThread();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });

    }
}


public class Runner {
    public void firstThread() throws InterruptedException
    {
    }

    public void secondThread() throws InterruptedException
    {
    }
}

1 个答案:

答案 0 :(得分:2)

您已经传递了一个实现Runnable的对象,尽管它是一个匿名类。

没有什么能阻止你把它拉进一个名为""等级,例如

public class RunnerFirstAction implements Runnable {
    private Runner runner;
    public RunnerFirstAction(Runner runner) {
        this.runner = runner;
    }
    @Override
    public void run() {
        runner.first();
    }
}

public class RunnerSecondAction implements Runnable {
    private Runner runner;
    public RunnerSecondAction(Runner runner) {
        this.runner = runner;
    }
    @Override
    public void run() {
        runner.second();
    }
}


public class Main{

    static Runner r1 =new Runner();
    public static void main(String[] args) {
        Thread t1 = new Thread (new RunnerFirstAction(runner));
        Thread t2 = new Thread (new RunnerSecondAction(runner));
        //....
    }
}