[英]Java Get multiple threads of different classes to run concurrently
我不确定问题到底是什么,但是由于某种原因,我无法从两个类中同时运行线程。 我可以从一个类中同时运行多个线程,但是当我尝试启动另一个类时,什么也没有发生。
public professor(){
prof = new Thread();
prof.start();
System.out.println("Prof has started1");
}
public void run(){
try{
System.out.println("Prof has started2");
prof.sleep(600);
//do more stuff
}
catch(Exception e){
System.out.println("Prof error");
}
这就是我开始第二堂课的方式,第一堂课以完全相同的方式开始并且运行良好。 但是,在该类中显示“教授已开始1”,但第二个从不显示。 我想念什么吗?
我认为这是原因
prof = new Thread();
prof.start();
此代码永远不会调用您自己的run()
方法,如果您的类实现了runnable接口,则应执行此操作
prof = new Thread(this)
prof.start()`
您没有提供完整的Professor类,所以确切的解决方案可能有所不同,但是我要注意的重点是:创建Thread
类的实例,然后调用.start()
:
prof = new Thread();
prof.start()
,当您在其上调用.start()
时, Thread
类本身不会执行任何操作。 您需要告诉它,一旦它被start()
ed后,您希望它执行什么动作。 有几种方法可以做到这一点,但我会这样做:
public professor() {
prof = new Thread(new Runnable() {
public void run() {
try {
System.out.println("Prof has started2");
Thread.currentThread().sleep(600);
//do more stuff
}
catch(Exception e){
System.out.println("Prof error");
}
}
});
prof.start();
System.out.println("Prof has started1");
}
public void run() {
}
那就是:创建一个Runnable
实例,在其中您重写run()
使其可以执行您想要的任何操作。 然后将此Runnable
实例传递给您正在创建的Thread
对象的构造函数。 当您随后调用.start()
将run()
该Runnable
的run()
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.