Home > Java > javaTutorial > Java: Define and start threads inside methods using anonymous inner classes

Java: Define and start threads inside methods using anonymous inner classes

高洛峰
Release: 2016-12-15 13:17:56
Original
1439 people have browsed it

The following code shows how to define a Thread through an anonymous inner class in a method, Override its run() method, and then start the thread directly.

Such code can be used to perform a side task by starting a new thread within a class. Generally, such tasks are not the main design content 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();
    }
}
Copy after login

Result:

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)


More Java: Use anonymous inner classes to define and start threads inside methods. For related articles, please pay attention to PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template