Java Core API--13 (threads)

Source: Internet
Author: User

1. Thread-related concepts

Process: One operating system can run multiple tasks (programs) at the same time, and each running task (program) is called a process.

Threads: A program may run multiple tasks at the same time (sequential execution flow), then each task (sequential execution flow) is called a thread. That is, inside the process.

Concurrency: threads are running concurrently. The operating system divides the time into several fragments (time slices), distributes as evenly as possible to each task, and when the time slice is allocated, the task has the opportunity to be executed by the CPU. On the microscopic level, every task is a walk and stop. But as the CPU runs efficiently, all tasks are running on the macro. This behavior is called concurrency, but not "simultaneous" in absolute sense.

Thread scheduling: The thread scheduling mechanism will be all concurrent tasks to do a unified scheduling work, divided into time slices (can be the time of the cup execution) to each task, the time slice as evenly as possible, but do not get absolutely uniform. Similarly, after the time slice is allocated, the task is executed by the CPU, but the scheduling process does not guarantee that all tasks are averaged over the number of times the time slice is acquired. Can only do as evenly as possible. Both are programs that are not controllable.

Start and stop of thread: void Start (): Do not call the Run method directly if you want to do concurrency! Instead, the calling thread's start () method starts the thread! void Stop (): Do not use the Stop () method to stop a thread from running, which is an unsafe operation that wants the thread to stop and should be finished by the Run method.


2. How threads are Created

1) inherit from thread and rewrite the Run method: The Run method should define the task logic code that we need to execute concurrently.

Case 29:

650) this.width=650; "title=" clipboard 29.png "src=" http://s3.51cto.com/wyfs02/M01/72/74/wKioL1XkHw_Au1k0AAEdp_ 2fbds855.jpg "alt=" Wkiol1xkhw_au1k0aaedp_2fbds855.jpg "/>

2) Implement Runnalbe interface. Because of this design, there is a thread pool.

Runnable interface: Used to define the task logic to be performed by the thread. When we set a class to implement the Runnable interface, we have to rewrite the Run method, where we define the logic we want to execute. The runnable is then handed over to the thread to execute. This allows the threads to split away from the tasks they perform. By handing the tasks to different threads for concurrent processing, you can use the thread's overloaded construction method: Thread (Runnable Runnable). Decoupling: The thread is decoupled from the thread body, which interrupts the dependency.

Case 30:

650) this.width=650; "title=" clipboard 30.png "src=" http://s3.51cto.com/wyfs02/M01/72/77/ Wkiom1xkhqurc71gaahejxulvvg919.jpg "alt=" Wkiom1xkhqurc71gaahejxulvvg919.jpg "/>

3) How threads are created three: creating Threads using anonymous inner classes

Case 31:

650) this.width=650; "title=" clipboard 31.png "src=" http://s3.51cto.com/wyfs02/M00/72/77/ Wkiom1xkhydxqy8daagtn4crdx8701.jpg "alt=" Wkiom1xkhydxqy8daagtn4crdx8701.jpg "/>

3. Thread Life cycle

The life cycle of a thread has 5 states: Create (new), Ready (runnable), run (running), block (block), Die (dead).

650) this.width=650; "title=" Clipboard.png "src=" http://s3.51cto.com/wyfs02/M02/72/77/ Wkiom1xkhblcs75haadsupcila4457.jpg "width=" 627 "height=" + "alt=" wkiom1xkhblcs75haadsupcila4457.jpg "/>

4. Common methods of threading

①static void Sleep method: Let the current thread actively enter the block blocking state and return to the Runnalbe state after time milliseconds. Note: When using the Thread.Sleep () method to block threads, forcing us to catch "break exceptions".

Case 32:

650) this.width=650; "title=" clipboard 32.png "src=" http://s3.51cto.com/wyfs02/M00/72/74/wKioL1XkH_XxbiUlAAErD5_ Kcwm971.jpg "alt=" Wkiol1xkh_xxbiulaaerd5_kcwm971.jpg "/>

②void Interrupt () Method: Interrupts/Wakes the thread. One thread can wake up the thread of another sleep block in advance.

Note: The class defined in the method is called a local inner class: In a local inner class, the variable must be final if it wants to refer to other local variables of the current method.

Case 33:

650) this.width=650; "title=" clipboard 33.png "src=" http://s3.51cto.com/wyfs02/M01/72/74/ Wkiol1xkibghtz1iaalm42j1ore541.jpg "width=" 622 "height=" 541 "alt=" wkiol1xkibghtz1iaalm42j1ore541.jpg "/>

③static void Yield (): The current thread gives up the processor (leaving the running state) to discard the current time slice and actively enters the runnable state wait.

④final void setpriority (int): Sets the thread priority, and the higher the priority thread, the more times the CPU is theoretically fetched. But there is a gap between the ideal and the reality ... Set the thread priority must be set before the threads start!

Case 34:

650) this.width=650; "title=" clipboard 34.png "src=" http://s3.51cto.com/wyfs02/M01/72/74/ Wkiol1xkic7wng47aaitbfgu9js704.jpg "width=" 578 "height=" 479 "alt=" wkiol1xkic7wng47aaitbfgu9js704.jpg "/>

5. Wait and Notify methods

These two methods are not the methods defined in thread threads, which are defined in object. Two methods are used to coordinate the work of a thread.

(1) The wait mechanism is closely associated with the lock mechanism: The Wait/notify method must be used in conjunction with synchronized, who calls the wait or Otify method, and locks who!

(2) Wait () method: Waits when the bar is not satisfied. When the condition is met, the thread that waits for the condition is awakened. such as: The browser displays a picture, displaythread to display the picture, you must wait for the download thread downloadthread the picture to complete download. Dialpaythread can be paused if the picture does not have a clutter complete. When the Downloadthread download is complete, the notification Displaythread can be displayed again, and Displaythread continues to execute.

(3) Notify () method: Randomly notifies, wakes up a thread waiting on the current object.

(4) Notifyall method: Notifies, wakes up all threads waiting on the current object.


6. Daemon Threads

The daemon background thread is also known as the daemon thread: After the "All", "foreground" thread dies in the current process, the background thread will be forced to die (unnatural death), whether or not it is still running.

The ① daemon thread must be called before the thread is started.

The ②main method is also run on a thread and is a foreground thread.

Case 35:

650) this.width=650; "title=" clipboard 35.png "src=" http://s3.51cto.com/wyfs02/M02/72/78/ Wkiom1xkhjcdw3mxaajrju0ibwm526.jpg "width=" 634 "height=" 460 "alt=" wkiom1xkhjcdw3mxaajrju0ibwm526.jpg "/>

7. Concurrency Security for Threads

multithreading can cause unsafe operations when accessing the same data (write operations).

① Synchronous Asynchronous:

Synchronization: Only one execution at a time, A and B work together, unison processing (b Get the result of a to continue). Like a group of people swipe on the bus.

Async: can have multiple executions at the same time, concurrently, each doing their own. Like a group of people riding bicycles.

②synchronized can be modified or exist separately as a block of statements (synchronous blocks). The effect is to restrict multithreading concurrency while accessing the scope at the same time.

The method is locked after the ③synchronized method is modified. The method is not asynchronous, but synchronous. The lock is the current object.

④synchronized Sync Block: Analyze that only one piece of code needs to be locked, then use. The efficiency is higher than the direct modification method.

⑤ thread safety is inefficient, such as vectors, Hashtable. Thread insecurity is high efficiency, such as ArrayList, HashMap.

Case 36:

650) this.width=650; "style=" WIDTH:670PX;HEIGHT:497PX; "title=" clipboard 36-1.png "src=" http://s3.51cto.com/wyfs02/ M01/72/74/wkiol1xkihsth7rdaahnmxfeayg719.jpg "width=" 698 "height=" 528 "alt=" wkiol1xkihsth7rdaahnmxfeayg719.jpg "/ >

650) this.width=650; "style=" width:672px;height:346px; "title=" clipboard 36-2.png "src=" http://s3.51cto.com/wyfs02/ M00/72/74/wkiol1xkikewuqqvaaili56m_na805.jpg "width=" 758 "height=" 406 "alt=" wkiol1xkikewuqqvaaili56m_na805.jpg "/ >

This article is from "Forever Young" blog, please be sure to keep this source http://kingkongzhao.blog.51cto.com/6319491/1690215

Java Core API--13 (threads)

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.