Thread
There are multiple way to create a thread.
Extends Thread
A thread can be created if we extends Thread
super class:
package domain;
public class CustomThread extends Thread{
private String name;
public CustomThread(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println("My thread running: " + name);
}
}
We can then run this thread as the following
ort domain.CustomThread;
public class Application {
public static void main(String[] args) {
CustomThread customThread = new CustomThread("thread1");
customThread.start();
CustomThread customThread2 = new CustomThread("thread2");
customThread2.start();
CustomThread customThread3 = new CustomThread("thread3");
customThread3.start();
}
}
Which results
My thread running: thread1
My thread running: thread3
My thread running: thread2
Note: When we call Thread.start()
, the order is not guaranteed
Implements Runnable (recommendation)
You can implements Runnable
. This is recommended as Java only allow 1 extends. as a result, we can do something like this
public class Player extends User implements Runnable {
@Override
public void run() {
}
}
To run, we can do
import domain.Player;
public class Application {
public static void main(String[] args) {
Thread playerThread = new Thread(new Player("test1"));
playerThread.start();
Thread playerThread2 = new Thread(new Player("test2"));
playerThread2.start();
Thread playerThread3 = new Thread(new Player("test3"));
playerThread3.start();
}
}