调用 run 方法而不启动新线程
请,如果我实现这样的代码会产生什么结果,
public class MyName implements runnable {
Thread t;
boolean checkinstance_state = false;
/*then in a method somewhere in the class i have something like this*/
public void firstOperation {
/*do something and then call setBlah()*/
setBlah();
}
public void setBlah(){
if(checkedinstance_state){
t = new Thread();
t. start();
checkedinstance_state = true;
} else {
t.run();
}
}
public void run(){
/*another method operation here*/
setBlahBlah();
}
}
请记住我已经实现了一个可运行的代码。情况是,我将定期访问此类,并且我不想一直创建线程对象。所以我想要一种情况,如果已经创建了线程对象,则应该调用 run 方法。这是正确的做法吗?是否会涉及到我在此实施中无法预见的问题?谢谢。
please, what will be the outcome if i implement a code like this
public class MyName implements runnable {
Thread t;
boolean checkinstance_state = false;
/*then in a method somewhere in the class i have something like this*/
public void firstOperation {
/*do something and then call setBlah()*/
setBlah();
}
public void setBlah(){
if(checkedinstance_state){
t = new Thread();
t. start();
checkedinstance_state = true;
} else {
t.run();
}
}
public void run(){
/*another method operation here*/
setBlahBlah();
}
}
Bearing in mind i am already implementing a runnable. Case is, i will keep accessing this class periodically, and i don't want to be creating a thread object all the time. so i want a situation that if a thread object has been created already, the run method should be called instead. is this a correct thing to do and will there issues involved, that i can't foresee in this implementation? Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以调用 run() 方法,但代码将在您调用该方法的当前线程中运行,而不是像您期望的那样在线程实例 (t) 中运行。
You can call the run() method, but the code will run in the current thread where you call the method, not in the thread instance (t) as you expect.
您应该有 if 条件,
因为在您的代码中,线程对象根本不会被初始化。
这样Thread对象第一次会被初始化并启动,当Thread对象进入
runnable
状态时,JVM会自行运行run方法。从那时起,每当您调用 setBlah() 时,都会在当前线程中显式调用 run 方法。you should have the if condition as
because with your code the thread object will not at all get initialized.
So that for the first time Thread object will be initialized and started, and JVM will run the run method by itself when the threaed objects enters the
runnable
state. and from then on whenever you call thesetBlah()
then therun
method will be called explicitly in the current thread.这不会做你想做的事。创建执行器服务,并定期将可运行实例传递给执行器;您不希望该类进行自己的线程管理,也不希望自己管理线程。执行器服务旨在将您与线程处理隔离。
This will not do what you want it to do. Create an executor service, and pass instances of the runnable to the executor on a regular basis; you don't want the class to do its own thread management, nor do you want to manage the threads yourself. The executor services were designed to isolate you from the thread processing.