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)