简体   繁体   English

如何从线程中调用与run()不同的方法

[英]How can I call a different method than run() from a Thread

Let's say I have a post() and a get() method that I want to run from a different thread. 假设我有一个post()get()方法,我想从另一个线程运行。 Is it possible to do this with just one class that extends Thread , where those methods are not in the run() method? 是否可以仅使用一个扩展Thread类来执行此操作,而这些方法不在run()方法中?

I thought of this: 我想到了这一点:

XYThread xy = new XYThread();
xy.start();
xy.post();
xy.get();

But in this case, would it still would be multithreading after the run() method is finished? 但是在这种情况下,在run()方法完成之后是否仍将是多线程的?

Do the work inside the run method; 做好内部的工作run方式; and call whatever methods you wish to call. 并调用您想调用的任何方法。

However, run and only run is called "within" the thread. 但是, runonly run称为线程“内”。 In the posted code both post and get are not executed within the context of the xy thread; 在发布的代码中, postget不会xy线程的上下文中执行; but instead in the context of the current thread. 而是在当前线程的上下文中。

It is also possible to supply a Runnable to a thread, which once again has its run method invoked, such that the Thread does not need to be sub-classed. 还可以向线程提供Runnable,该线程再次调用其run方法,这样就不必对Thread进行子类化。 And yes, at some level this means creating different classes or otherwise embedding logic. 是的,在某种程度上,这意味着创建不同的类或嵌入逻辑。

只需从run()方法调用它即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM