The use of multi-threading, the application scenarios of synchronization locks, the status of threads

1. [The class inherits the] Thread class, [overrides the run() method,] calls start(), which is not suitable for resource sharing.

public class ThreadDemo1 extends Thread{

    //Add a constructor to easily distinguish new threads 
    public   ThreadDemo1 (String name)  {
         super (name);
    }

    @Override
    public void run() {
    System.out.println(Thread.currentThread().getName()+i);
    }
    public static void main(String[] args) throws InterruptedException {

        ThreadDemo1 demo1 = new ThreadDemo1( "Xiaoqiang" );     
        demo1.start();
        System.out.println(Thread.currentThread().getName()+i);
    }
}

2. The class implements the Runable interface, [override the run() method,] call start()

public class Runable1 implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "***" + i);
    }
    public static void main(String[] args) {
        Runable1 runable1 = new Runable1();
        Thread thread = new Thread(runable1);
        thread.start();
    }

3. Use an anonymous inner class (same implementation as method 2, but the rewrite is different) Create a Thread object and pass in parameters (Runable interface) Runable is an anonymous inner class, and at the same time rewrite Run() in Runable method. Finally call the start() method of the Thread object

Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    System.out.println(Thread.currentThread().getName()+i);
                }
            }
        });
        thread.start();

Threads reflect the simultaneous work of multiple method stacks at the same time. To reflect this effect, for (int i = 0; i < 10; i++) is added to output several times, and it can also be combined with thread.sleep (milliseconds).

sync lock

  1. Synchronized code blocks (recommended)

//Lock object Object, there are wait (release lock object, program stop) and notify (notify the thread currently on this lock object to wake up and run) 
//When using wait and notify, to ensure that the lock object is the same, it is still necessary to use Synchronous code is a fast way, instead of using the synchronization method 
//There is no wait and notify method in the ReentrantLock class 
private  final Object obj= new Object();
 //As long as it is the same Monitor, it doesn't matter whether the properties of the Monitor change 
@Override is 
    not modified with final public  void  run ()  {
         //synchronized code block 
        synchronized (obj){
        }

  1. Synchronized method

//Synchronized method lock object this 
    public  synchronized  void  sellTicket ()  {
    }

  1. ReentrantLock

private ReentrantLock lock = new ReentrantLock();
 // Add lock .lock () at the beginning where synchronization locks are required
 ;
 //end lock .unlock();

the state of the thread

See the public enum State of java.lang.Thread

A thread can be in one of the following states:
A thread can be in one of the following states:
NEW 
A thread that has not yet started is in this state.
NEW A thread that has not been started is in this state.
RUNNABLE 
A thread executing in the Java virtual machine is in this state.
RUNNABLE Threads executing on the Java Virtual Machine are in this state.
BLOCKED 
A thread that is blocked waiting for a monitor lock is in this state.
A blocked thread that is waiting for a monitor lock is in this state.
WAITING 
A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
A thread that is waiting indefinitely for another thread to perform a particular operation is in this state.
TIMED_WAITING 
A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
A thread that waits for another thread to perform an operation within the specified wait time is in this state.
TERMINATED 
A thread that has exited is in this state.
An exited thread is in this state.
A thread can be in only one state at a given point in time.
A thread can only be in one state at a given point in time.
These states are virtual machine states which do not reflect any operating system thread states.
These states are virtual machine states that do not reflect the state of any operating system threads.
Since:1.5
See Also:
getState

Thread synchronization using CountDownLatch

import java.util.concurrent.CountDownLatch;

public class CountDownLatchDemo {

    static class TaskThread extends Thread {

        CountDownLatch latch;

        public TaskThread(CountDownLatch latch) {
            this.latch = latch;
        }

        @Override 
        public  void  run ()  {
             //Process business 
            System.out.println(Thread.currentThread().getName() + " Task is Done" );
             // Count down by one
            latch.countDown();
        }

    }

    public static void main(String[] args) throws InterruptedException {

        int threadNum = 10;
        CountDownLatch latch = new CountDownLatch(threadNum);
        System.out.println("Task Start!");
        for (int i = 0; i < threadNum; i++) {
            TaskThread task = new TaskThread(latch);
            task.start();
        }
        // If the current count of new CountDownLatch(threadNum) is greater than zero, the current thread is disabled for thread scheduling purposes and is dormant 
        . interrupt the current thread
        latch.await();

        System.out.println("All Task is Done!");
    }

}

Key code
When creating CountDownLatch, ensure that the number of threads created is the same as the count of the constructor. Decrement the counter by one using latch.countDown(); in the last step of creating a thread implementing the run() method .
In order to ensure that the creation thread has been executed , use latch.await() at the outermost layer;

Leave a Comment

Your email address will not be published. Required fields are marked *