Today’s sharing started, please give us more advice ~

First, the concept of threads

(1) process

A process is a running activity of a program with some independent function about a set of data.

Process characteristics

  • Structural features

  • dynamic

  • concurrency

  • independence

  • asynchrony

Process: The basic unit for allocating and managing resources during the execution of concurrent programs. It is a dynamic concept and the basic unit for competing computer system resources.

Multi-process: The ability to run more than one task (program) simultaneously in an operating system;

(2) threads

A thread (English: thread) is the smallest unit in which an operating system can schedule operations.

  • It is contained within the process and is the actual operating unit within the process.

  • A thread is a single sequential flow of control in a process, and multiple threads can be concurrent in a process, each performing a different task in parallel.

Thread: A unit of execution in a process. It is a schedulable entity within the process. A basic unit smaller than a process that runs independently. Threads are also called lightweight processes.

Multithreading: Multiple sequential streams executing simultaneously in the same application.

The purpose of multithreading is to maximize the utilization of CPU resources.

Second, thread creation

There are two ways to implement multithreading in Java:

Inherit the Thread class from the java.lang package.

Users implement the Runnable interface in their own classes.


1. The Thread class

Directly inherits the Object class, and implements the Runnable interface. Located in the java.lang package

Encapsulates properties and methods needed by thread objects

Inheriting the Thread class – one of the ways to create multiple threads

  • Subclass Thread and create objects for that subclass. Subclasses should override the Run method of Thread to write statements that need to be executed in the new Thread.

  • Call the start method to start a new thread, which automatically enters the run method.

2. A subclass of the Thread class to create threads

Define a subclass of Thread and override its run method:

Generate an object of this class:

MyThread myThread = new MyThread();

If you start or run a thread, the Java VIRTUAL machine automatically starts the thread. In this way, the Java Virtual machine schedules threads in a unified manner, enabling all threads to run concurrently.


The results are different each time. Because multiple threads acquire execution rights from the CPU, whoever the CPU executes executes executes. To be clear, only one program can be running at a time (with the exception of multicore).

The cpus are switching quickly so that they appear to be running simultaneously. We can think of multithreading as competing for CPU execution.

A feature of multithreading: randomness, who grabs, who executes, and how long to execute, determined by the CPU.

3. Finish calculating the factorial of an integer in a new thread

The results

The result shows that

  • The new thread will finish executing after the main thread has finished executing.

  • The main function calls thread.start() to start a new thread without waiting for its run method to return. The function runs on its own without affecting the original main function.

4. Constructor

Public Thread ();

Public Thread (Runnable target);

Public Thread (String name);

public Thread(Runnable target, String name);

Parameter Description:

Name: Name of the new thread object

5. Common methods

Public void the start ();

Starting the thread causes the run method to be invoked automatically. The method will return immediately and the new thread will run.

Public void the run ();

You must override the method by adding the code you want to execute in that thread to the body of the method.

Public static void sleep(long millis) throws InterruptedException;

Causes the currently executing thread to sleep for the specified time. Sleep () allows low-priority threads to execute, as well as same-priority, high-priority threads. The object lock is not released. That is, if a Synchronized block is present, other threads still cannot access the shared data. Note that this method catches exceptions.

Public static void yield();

This is similar to sleep(), except that the user cannot specify how long to pause, and yield() allows only threads of the same priority to execute.

Public Final Boolean isAlive();

Used to test whether a thread is still alive

Public final void setPriority(int newPriority);

Set the priority of the thread

public final int getPriority() ;

Get the priority of the thread

Public static Thread currentThread();

Returns a Thread object representing the currently executing Thread

Public final void Wait (Long timeout) throws InterruptedException;

The current thread is interrupted and placed on the wait list of an object until another thread calls notify() or notifyAll() on the same object

Public final void notify();

Use to wake up a selected thread in the object wait list and make it runnable again

Public final void notifyAll();

Use to wake up all threads in the object wait list and make them runnable again.


1. The Runnable interface

The Thread class implements the Runnable interface

There is only one run() method

Easier for multiple threads to share resources

Java does not support multiple inheritance, and if you already inherit a base class, you need to implement the Runnable interface to generate multiple threads

Create a new thread with an object that implements runnable

The start method starts the thread and runs the run() method

2. Use the Runnable interface

Use the Runnable interface implementation to compute the factorial of an integer

Three objects of type Runnable

Data sharing between threads

Independent concurrent threads sometimes need to share some data and take into account each other’s state and actions

Create multiple threads with the same object that implements the Runnable interface as a parameter

Multiple threads share the same data in the same object

The results

Starting threads

Thread1 going to sleep for 966

Thread2 going to sleep for 966

Threads started, main ends

Thread3 going to sleep for 966

Thread1 finished

Thread2 finished

Thread3 finished


Because three new threads were created with a Runnable object, they shared the object’s private member sleepTime, and all three threads slept for 966 milliseconds during the run.

Fourth, multi-thread synchronization control

(1) Synchronization method

Think of synchronized as a function modifier

Synchronized locks the object that calls the synchronized method.

When an object P1 executes this synchronization method on different threads, they are mutually exclusive and synchronized.

But P2, the Class of which this object belongs, can call the synchronized method at will.

A statically synchronized method, like a lock held by a synchronized(class) block, is a class lock, which applies to all instances of an object.

(2) Synchronize code segments

Synchronized Keyword for thread synchronization to achieve mutual exclusion:

Used to specify code segments or methods that need to be synchronized, i.e., monitor areas

Interaction with a lock flag can be implemented. Such as:

Synchronized (object)

The function of synchronized is: first judge whether the lock flag of the object is in, if it is, it will get the lock flag, and then it can execute the following code segment; If the lock flag of the object is not there (it has been taken by another thread), it enters the wait state until the lock flag is obtained

When the section of code qualified by synchronized is finished executing, the lock flag is released

Java uses the monitor mechanism

Each object has only one “lock flag”, the use of multi-thread to “lock flag” to achieve mutually exclusive threads

After thread A has acquired the lock flag of an object, thread B must wait for thread A to complete the specified operation and release the lock flag before it can acquire the lock flag of the object and perform the operation in thread B

(3) Simulate the process of ticket depositing and selling

Suppose there are no tickets at the beginning of the ticket office, and one thread deposits tickets in and another thread sells tickets out

Create a new ticket object and make it accessible to both the depositing and ticketing threads. In this example, two threads share the same data object to operate on the same data

1. No synchronization control is performed

2. Synchronize code snippets

Place the mutually exclusive statement segments into synchronized(object){} statements where the object is the same.

3. Synchronization method

Place the mutex methods in shared resource class Tickets

Today’s share has ended, please forgive and give advice!