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(); } }
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!