首页 > 解决方案 > 使用具有多个对象的单个线程?

问题描述

所以假设我有一个实现 Runnable 接口的类:

class Doctor implements Runnable{
    private String name;
    private int id;
    
    Doctor(String name, int id){
        this.name = name;
        this.id = id;
    }
    
    public void run(){ /* some code */}
}

现在Doctor类作为一个线程工作,但是我怎样才能从多个对象中获得Doctor类的一个线程?

例如:

Doctor d1 = new Doctor("George", 1);
Doctor d2 = new Doctor("Jim", 2);

如何启动单个线程并知道何时d1d2正在运行?

如果我运行:

Thread t1 = new Thread(d1);
Thread t2 = new Thread(d2);
t1.start();
t2.start();

然后在这里我创建两个线程而不是一个。

标签: javamultithreadingrunnablejava-threads

解决方案


推荐阅读