Threads are created & started & stopped

Threads are a good thing, but you rarely create your own threads, so some of the basic operations may not be easy to remember, and this article is always good for your health

1. Create
public class TestDeamon {
    public static void main(String[] args) {
        // lambda expressions
        Thread t1 = new Thread(()->System.out.println("This is a thread 01!"));
        Thread t2 = new Thread(()->{
            System.out.println("This is a thread 02!");
        });
        // Anonymous inner class
        Thread t3 = new Thread(){
            @Override
            public void run(a) {
                System.out.println("This is a thread 03!"); }};/ / Thread
        Thread t4 =new MyThread04();

        The Runnable argument is Runnable
        Thread t5 = new Thread(new MyRunnable());

        / / time
        // Start the threadt1.start(); t2.start(); t3.start(); t4.start(); t5.start(); }}/** * public class Thread implements Runnable */
class MyThread04 extends  Thread{
    @Override
    public void run(a) {
        System.out.println("This is thread 04!"); }}/** * implement Runnable */
class MyRunnable implements   Runnable{
    @Override
    public void run(a) {
        System.out.println("This is a thread 05!"); }}Copy the code
2. Start
// Start the threadt1.start(); t2.start(); t3.start(); t4.start(); t5.start(); Output: This is a thread01! This is a thread02! This is a thread03! This is a thread04! This is a thread05!Copy the code

Once the thread is started, the run method is executed

3. Stop the thread/interrupt
3.1. The thread terminates after execution

The for loop ends automatically after the for loop is executed

// lambda expressions
        Thread t1 = new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try{
                    Thread.sleep(1000);
                    System.out.println("= = =");
                } catch(Exception e) { e.printStackTrace(); }}}); t1.start();Copy the code
3.2. Stop is deprecated

Stop has been abandoned, stop is too rough, not gentle, so no one likes..

 // lambda expressions
Thread t1 = new Thread(()->{
    for (;;) {
        try{
            Thread.sleep(1000);
            System.out.println("= = =");
        } catch(Exception e) { e.printStackTrace(); }}}); t1.start();// Stop after 10 seconds
Thread.sleep(10000);
/ / stop
t1.stop();
Copy the code

It’s easy to create data inconsistencies because a transaction or a piece of code can get killed before it’s finished executing

Here’s an example:

// lambda expressions
Thread t1 = new Thread(()->{
    System.out.println("The object went to the shower.");
    try{
        System.out.println("Wait under the covers...");
        Thread.sleep(10000);
        System.out.println("The Shower.");
    } catch(Exception e) { e.printStackTrace(); }}); t1.start();// Stop after 10 seconds
Thread.sleep(5000);
/ / stopt1.stop(); Result: The object takes a shower, gets under the covers, and waits... As you can see, you waited for a long time and were interrupted before you could even start your retreat.Copy the code
3.3 Suspend Resume is obsolete

Suspend suspends a thread

Resume allows a suspended thread to resume execution

Suspend is subject to deadlocks and other problems. If a resume is forgotten or a resume exception occurs, the suspend thread is deadlocked if it holds a lock

public class TestDeamon03 {
    // Lock represents an object
    public static Object obj = new Object();
    public static void main(String[] args) throws InterruptedException {

        // lambda expressions
        Thread t1 = new Thread(()->{
                synchronized (obj){
                   try {
                       System.out.println("I went out to work and left my date at home.");
                       Thread.sleep(10000);
                       System.out.println("I came back to marry my date.");
                   } catch(Exception e) { e.printStackTrace(); }}}); t1.start();// Pause after 2 seconds
        Thread.sleep(2000);
        / / pause
        t1.suspend();
        Thread.sleep(2000);
		/ / recovery
        resumeObj(t1);
    }

    // Resume simulation is abnormal
    static void resumeObj(Thread t){
        int i = 1/0; t.resume(); }}Copy the code

You find an object, put her home, said to work for a year back to marry, and then you find someone on the way home, happy life together, your object at home…

Occupied by you, you do not notice, do not release

3.4 volatile end

The time that volatile modiates a variable may not be very precise because it’s volatile and then it’s flushed to memory and it’s read by another thread and it’s pretty fast but in general it’s fine, okay

public class TestDeamon04 {
    static volatile boolean flag = true;
    public static void main(String[] args) throws InterruptedException {
        // lambda expressions
        Thread t1 = new Thread(()->{
            int count =0;
            // flag== true loop flag==false Stop the loop and end the thread
            while (flag) {
                try {
                    Thread.sleep(1);
                    count++;
                } catch (Exception e){
                    e.printStackTrace();
                }
            }
            System.out.println("count:"+count);
        });

        t1.start();
        // Stop after 1 second
        Thread.sleep(1000);
        flag = false; }} multiple output results:505,525,507,512You can see that every time the output is indeterminate, this way you can only guarantee that the thread will stop when it reaches a certain condition but you can't tell the thread to stop exactly if you want to loop a thread100It is difficult to accurately control the stoppageCopy the code
3.5 end of the interrupt

Also a flag bit but a bit more advanced than volatile. Operations such as sleep and wait are interrupted

// lambda expressions
final Thread t1 = new Thread(()->{
    int count =0;
    //
    while(! Thread.interrupted()) {try {
            count++;
        } catch (Exception e){
            e.printStackTrace();
        }
    }
    System.out.println("count:"+count);
});

t1.start();
// Stop after 1 second
Thread.sleep(1000);
t1.interrupt();
Copy the code

Sleep can be caught with a break but flag is not

public class TestDeamon06 {
    static volatile boolean flag = true;
    public static void main(String[] args) throws InterruptedException {
        // lambda expressions
        final Thread t1 = new Thread(()->{
            //
            while(! Thread.interrupted()) {try {
                    Thread.sleep(20000000);
                } catch (Exception e){
                    break;
                }
            }
            System.out.println("Interrupted the end");
        });

        // lambda expressions
        final Thread t2 = new Thread(()->{
            while (flag) {
                try {
                    Thread.sleep(20000000);
                } catch (Exception e){
                    break;
                }
            }
            System.out.println("Volatile - end");
        });

        t1.start();
        t2.start();
        // Stop after 1 second
        Thread.sleep(1000);
        t1.interrupt();
        flag = false; }}Copy the code

Conclusion:

Stop and suspend resume are not used

The volatile flag cannot interrupt operations such as sleep Wait

InterruptedException is equivalent to a flag bit but can interrupt operations such as sleep Wait to catch InterruptedException for thread termination

There may be other ways mostly based on flag bits

Welcome to our official account: