Creating, Starting and Stopping Threads
Create
Using the Original Class
package com.guanlun.java.concurrency.thread;
public class ThreadExample {
public static void main(String[] args){
Thread thread = new Thread();
thread.start();
}
}
Inheritant from Thread Class
package com.guanlun.java.concurrency.thread;
public class ThreadExample2 {
public static class MyThread extends Thread{
public void run(){
System.out.println("MyThread running");
System.out.println("MyThread finished");
}
}
public static void main(String[] args){
MyThread myThread = new MyThread();
myThread.start()
}
}
Runnable Interface
Must implement the run method
package com.guanlun.java.concurrency.thread;
public class ThreadExample3 {
public static class MyRunnable implements Runnable{
@Override
public void run(){
System.out.println("MyRunnable running");
System.out.println("MyRunnable finished");
}
}
public static void main(String[] args){
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
Inheritant from Runnable Class
package com.guanlun.java.concurrency.thread;
public class ThreadExample4 {
public static class main(String[] args) {
Runnable runnable = new Runnable(){
@Override
public void run(){
System.out.println("Runnable running");
System.out.println("Runnable finished");
}
};
Thread thread = new Thread( runnable );
thread.start();
}
}
Implement Runnbale with Lambda Function
package com.guanlun.java.concurrency.thread;
public class ThreadExample5 {
public static class main(String[] args) {
Runnable runnable = () -> {
System.out.println("Runnable running");
System.out.println("Runnable finished");
};
Thread thread = new Thread( runnable );
thread.start();
}
}
Get and Set Thread Name
package com.guanlun.java.concurrency.thread;
public class ThreadExample6 {
public static class main(String[] args) {
Runnable runnable = () -> {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " running");
};
Thread thread = new Thread( runnbale, "NewThreadName");
thread.start(); //NewThreadName
Thread thread2 = new Thread( runnbale, "NewThreadName2");
thread.start(); //NewThreadName2
}
}
Join/Wait a Thread
Wait for the Java Thread to terminate
package com.guanlun.java.concurrency.thread;
public class ThreadExample7 {
public static class main(String[] args) {
Runnable runnable = () -> {
for (int i=0; i<5; i++){
sleep(1000);
System.out.println("Running")
}
};
Thread thread = new Thread(runnbale);
thread.setDaemon(true);
//the Daemon thread's life depends on the user thread
//when the main thread is finished, then Daemon thread is also terminated.
thread.start();
//if here is the end of the main program, then there is nothing happen, because the thread is a Daemon thread, and the main is already finished.
try {
thread.join();
//the main thread will be blocked(Waiting Here) until the thread is terminated.
} catch (InterruptedException e) {
e.printStackTrace()
}
}
}