Java Thread Class
Thread Class
The approach using the Thread class extends the java.lang.Thread class and overrides the run method. The run method is the method executed by the thread, and developers write the code to execute in this method.
Example 1) Running one Thread The following example implements and creates a class by extending Thread.
package com.devkuma.tutorial.thread;
public class MyThread extends Thread {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("This is thread. i=" + i);
}
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
Result:
This is thread. i=0
This is thread. i=1
This is thread. i=2
This is thread. i=3
This is thread. i=4
This is thread. i=5
This is thread. i=6
This is thread. i=7
This is thread. i=8
This is thread. i=9
Because only one thread is executed, you can see the same result as a normal loop.
Example 2) Running two Threads
The following example looks at the case with two threads.
package com.devkuma.tutorial.thread;
public class MyThread2 extends Thread {
public MyThread2(String name) {
super(name);
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(super.getName() + " thread. i=" + i);
}
}
public static void main(String[] args) {
MyThread2 thread1 = new MyThread2("first");
MyThread2 thread2 = new MyThread2("second");
thread1.start();
thread2.start();
}
}
Result:
first thread. i=0
first thread. i=1
second thread. i=0
second thread. i=1
second thread. i=2
first thread. i=2
second thread. i=3
second thread. i=4
second thread. i=5
second thread. i=6
second thread. i=7
second thread. i=8
second thread. i=9
first thread. i=3
first thread. i=4
first thread. i=5
first thread. i=6
first thread. i=7
first thread. i=8
first thread. i=9
Compared with Example 1, you can see that the first thread and second thread run irregularly and display their own results.