Java Fundamentals-Threading

Source: Internet
Author: User

1. What do you mean by threading

Process: A program in progress

Threads: Lightweight processes, sequential flow of control in a program, can be understood as different execution paths in a program

The thread Cheng is the Run () method (directly called run () as the normal method), and the start thread is the start () method

2. Five states of a thread

Create : Two ways of inheriting the Thread class, overriding the run () method, implementing the Runnable interface, implementing the Run () method

  Ready : Call the Start () method of the thread (the second way to implement the interface is to use a static proxy)

  run : Get time slices, start running

  blocking : encountering blocking events

  termination : Thread death, prohibit the use of the Stop () method, but should define a Boolean flag, and in the Run () method to judge the flag to reasonably end the run () method to end the thread.

3. Thread Common methods

  Thread.Sleep (): thread sleep , parameter is the number of sleep milliseconds for the current thread. (static method). sleep with the lock on

Join (): A thread merge that merges the current thread with the thread, waiting for the thread to terminate

Yield (): thread concession, yielding CPU

Wait (): The thread waits for the current thread to go into the wait pool thread. Discard lock Wait

Notify ()/notifyall (): Wake on thread , wake up one/all threads in the waiting pool

4. Thread synchronization

  Object mutex: Synchronized (obj) guarantees that only one thread at a time can access the object, guaranteeing the operational integrity of the shared data.

Synchronization is generally divided into two categories (attention to deadlock problems):

      Synchronization method

        Public synchronized void Fun1 () {}

      Synchronization block

        Synchronized (this) {}

Troubleshooting thread deadlock It's best to lock only one object, not two objects at a time

The classic producer consumer model

Java Fundamentals-Threading

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.