Java multithreading -- the creation and use of threads

Keywords: Java

1, Two ways to create threads

1. Inherit from Thread class

1. Create a subclass inherited from the Thread class
2. Rewrite run() of Thread class to declare the operation performed by this Thread in run()
3. Create the object of the subclass of Thread class
4. Call start() through this object: ① start the current thread ② call the run() of the current thread

public class ThreadTest {
    public static void main(String[] args) {
        MyThread t = new MyThread();
        t.start();

        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0){
                System.out.println(i + "****main()******");
            }
        }
    }
}

class MyThread extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0){
                System.out.println(i);
            }
        }
    }
}

Explain:

1. When we start a thread, we must call start() instead of run().

2. If you start another Thread, you must recreate the object of a Thread subclass and call start() of this object. If start() is called directly without overriding the creation object, an exception of java.lang.IllegalThreadStateException will be thrown.

To create a multithread by anonymous subclass:

public class ThreadDemo {
    public static void main(String[] args) {

        new Thread(){
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    if (i % 2 == 0){
                        System.out.println(Thread.currentThread().getName() + ":" + i);
                    }
                }
            }
        }.start();

        new Thread(){
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    if (i % 2 != 0){
                        System.out.println(Thread.currentThread().getName() + ":" + i);
                    }
                }
            }
        }.start();
    }
}

2. Implement the Runnable interface

1. Create a class that implements the Runnable interface
2. Implementation class to implement the abstract method in Runnable: run()
3. Create the object of the implementation class
4. Pass this object as a parameter to the constructor of Thread class, and create the object of Thread class
5. Call start() through the object of Thread class

public class ThreadTest {
    public static void main(String[] args) {
        MThread m1 = new MThread();
        Thread t1 = new Thread(m1);

        t1.setName("Thread 1");
        t1.start();

        Thread t2 = new Thread(m1);
        t2.setName("Thread 2");
        t2.start();
    }
}

class MThread implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}

2, Common methods in Thread class

1. start(): start the current thread; call the run() of the current thread
2. run(): you usually need to override this method in the Thread class and declare the operation to be performed by the created Thread in this method
3. currentThread(): a static method that returns the thread executing the current code
4. getName(): get the name of the current thread
5. setName(): set the name of the current thread

6. yield(): release the execution right of the current cpu

public class ThreadMethodTest {
    public static void main(String[] args) {
        HelloThread h1 = new HelloThread("Thread 1");

//        h1.setName("Thread one");//Name the thread
        h1.start();

        //Name the main thread
        Thread.currentThread().setName("Main thread");
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0){
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}

class HelloThread extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0){
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
            if (i % 20 == 0) {
                yield();
            }
        }
    }

    //Name the thread by constructor
    public HelloThread(String name){
        super(name);
    }
}

7. join(): join() that calls thread b in thread a. At this point, thread a enters a blocking state until thread b is fully executed, and thread a ends the blocking state.

8. stop(): obsolete. When this method is executed, forces the end of the current thread.

9. Sleep (long duration): lets the current thread "sleep" the specified duration milliseconds. The current thread is blocked for the specified millitime milliseconds.

10. isAlive(): judge whether the current thread is alive

public class ThreadMethodTest {
    public static void main(String[] args) {
        HelloThread h1 = new HelloThread();

        h1.setName("Thread one");//Name the thread
        h1.start();

        //Name the main thread
        Thread.currentThread().setName("Main thread");
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0){
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
            if (i == 20){
                try {
                    h1.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        System.out.println(h1.isAlive());//false Determine whether the thread survives
    }
}

class HelloThread extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0){
                try {
                    sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}

3, Priority of thread

1. Three levels:

MAX_PRIORITY: 10
MIN _PRIORITY: 1
Norm? Priority: 5 > default priority

2. Two methods:

getPriority(): get the priority of the thread
setPriority(int p): set the priority of the thread

Explain:

The high priority thread should preempt the execution power of the low priority thread cpu. But only in terms of probability, high priority threads are executed with high probability. It doesn't mean that low priority threads only execute after high priority threads have finished executing.

public class ThreadMethodTest {
    public static void main(String[] args) {
        HelloThread h1 = new HelloThread();

        h1.setName("Thread one");//Name the thread
        h1.setPriority(Thread.MAX_PRIORITY);
        h1.start();

        //Name the main thread
        Thread.currentThread().setName("Main thread");
        Thread.currentThread().setPriority(Thread.MIN_PRIORITY);

        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0){
                System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getPriority() + ":" + i);
            }
        }
    }
}

class HelloThread extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0){
                System.out.println(Thread.currentThread().getName() + ":" + getPriority() + ":" + i);
            }
        }
    }
}

 

 

Author: the beauty of Java

Date: March 30, 2020

Posted by rilana on Mon, 30 Mar 2020 02:57:09 -0700