Java: Using anonymous inner classes to define and start a thread inside a method

Source: Internet
Author: User

The following code shows a method that defines a thread through an anonymous inner class and override its run () method and then starts the thread directly.

Such code can be used to perform a branch task within a class by using another thread, which is not the main design of the class.

Package com.zj.concurrency;

public class StartFromMethod {
  private Thread t;
  private int number;
  private int count = 1;
  public StartFromMethod(int number) {
    this.number = number;
  }
  public void runTask() {
    if (t == null) {
      t = new Thread() {
       public void run() {
         while (true) {
           System.out.println("Thread-" + number + " run " + count
              + " time(s)");
           if (++count == 3)
             return;
         }
       }
      };
      t.start();
    }
  }
  public static void main(String[] args) {
    for (int i = 0; i < 5; i++)
      new StartFromMethod(i).runTask();
  }
}

Results:

Thread-0 run 1 time(s)
Thread-0 run 2 time(s)
Thread-1 run 1 time(s)
Thread-1 run 2 time(s)
Thread-2 run 1 time(s)
Thread-2 run 2 time(s)
Thread-3 run 1 time(s)
Thread-3 run 2 time(s)
Thread-4 run 1 time(s)
Thread-4 run 2 time(s)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.