开发者

How can I execute statements in parallel, if I can't extend Thread (since I'm already extending another class)?

开发者 https://www.devze.com 2023-03-28 14:03 出处:网络
public class Sample extends Panel { // Constructor public Sample() throws IOException { /* JobOne and JobTwo need to be implemented 开发者_运维问答using Thread at same time */
public class Sample extends Panel {

  // Constructor
  public Sample() throws IOException {

     /* JobOne and JobTwo need to be implemented 开发者_运维问答using Thread at same time */

     JobOne{
       //statements
     }

     JobTwo{
       //statements
     }

  }

  public static void main(String[] args) throws IOException {
     new Sample();
  }
}

How to perform this, if need these things to be implemented inside the constructor?


Don't extend Thread, implement java.lang.Runnable. That way you can extend from another class.

You can run it in its own thread like:

Thread thread = new Thread(myRunnable).start();

Also this way the Runnable isn't locked into being run as an individual thread, it can be handed to an Executor.

See this article on safe construction techniques for why you shouldn't start a thread from a constructor.

0

精彩评论

暂无评论...
验证码 换一张
取 消