java multi-threaded learning and use of detailed analysis.

Posted by thegman on Wed, 13 Nov 2019 18:37:26 +0100

Multithreaded learning.

1.2 thread creation and startup.

The first way: inherit Thread.
package com.chen;

/**
 * @program: java Advanced related knowledge
 * @description: By inheriting Thread class to create multithreading, instance variables of Thread class cannot be shared among multiple threads.
 * @author: Mr.Chen
 * @create: 2019-05-09 16:57
 **/
public class FirstThread extends Thread {
    private int i;
    // Rewrite the run() method. The method of the run() method is the thread execution body
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println(getName() + "## " + i);
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            // Call the method of currentThread() of Thread to get the current Thread
            System.out.println(Thread.currentThread().getName() + ": " +i);
            if (i == 20) {
                // Create and start the first thread
                new FirstThread().start();
                new FirstThread().start();
            }
        }

    }
}
The second is to implement the Runnable interface
package com.chen;
/**
 * @program: java Advanced related knowledge
 * @description: Create the object of Runnable implementation class
 * @author: Mr.Chen
 * @create: 2019-05-09 17:10
 **/
public class SecondThread implements Runnable {

    private int i;
    // The run() method is also a thread execution body.
    public void run() {
        for (; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + "# " + i);
        }
    }

    /**
     * Using Runnable interface to create multiple threads can share the instance properties of thread class.
     * Because: the Runnable object created by the program is only the target of the thread, and multiple threads can share a target,
     * Therefore, multiple threads can share the instance properties of the same thread class (actually, it should be the target class of the thread),
     */
    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + ": " + i);
            if (i == 20) {
                SecondThread st = new SecondThread();
                new Thread(st,"New thread 1").start();
                new Thread(st,"New thread 2").start();
            }
        }
    }
}
The third is to implement the Callable interface with return value.
package com.chen;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @program: java Advanced related knowledge
 * @description: Implement the Callable interface to implement the thread class
 * @author: Mr.Chen
 * @create: 2019-05-09 17:23
 **/
public class ThirdThread implements Callable<Integer> {
    // Implement the call method as the thread execution body.
    public Integer call() throws Exception {
        int i = 0;
        for (; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + "Loop variable of i Value " + i);
        }
        return i;
    }

    public static void main(String[] args) {
        // Create Callable object
        ThirdThread rt = new ThirdThread();
        // Use FutureTask to wrap the Callable object.
        FutureTask<Integer> task = new FutureTask<Integer>(rt);
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + "Loop variable of i Value " + i);
            if (i == 20) {
                // In essence, the Callable object is used to create and start the thread.
                new Thread(task,"Thread with return value").start();
            }
        }
        try {
            // Get thread return value
            System.out.println("Return value of child thread:" + task.get());
            // This method causes the main thread to block until the call () method ends and returns.
        }  catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Three ways to create threads.

Creating multithreading by implementing Runnable and Callable interfaces

Advantages:

  • Thread classes are only based on Runnable and Callable interfaces, and can inherit other objects.
  • Multiple threads can share the same target object, which is suitable for multiple threads to process the same object, so as to separate cpu, code and data, form a clear model, and better reflect the idea of object-oriented.

Inferiority:

  • Programming is relatively complex. If you need to access the current thread, you must use the Thread.currentThread() method.

Creating multi threads by inheriting Thread class

Inferiority:

  • Thread already inherits thread class, cannot inherit other base class.

Advantages:

  • Write simply, access the current thread, and directly use this to get the current thread.

1.3 thread life cycle

Topics: Programming Java