Java basics 3: multithreading and java Multithreading

Source: Internet
Author: User

Java basics 3: multithreading and java Multithreading

I think I can write well on the basics of Java. I used to post it on my other blog. It must be original. I will share it with you now.

Zookeeper ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------




It is easier to implement only one task at a time, but in fact many tasks are executed at the same time. java introduces a thread mechanism to simulate this state.

When a program completes multiple tasks at the same time, it is called a multi-threaded program.

At one time point, a single-core cpu can only run one program. What we can see is that the cpu performs a fast random switching between multiple processes.

Therefore, multithreading solves the problem of Running multiple concurrent threads, but too many threads will definitely affect the efficiency.

First, we will show what we will introduce in a regular chart:

I. Implementation Method

There are two ways to implement the Thread: Inherit the Thread class and implement the Runnable interface.

1. inherit the Thread class.

A. The definition class inherits the Thread.

B. re-write the run method in the Thread.

C. Create an instance object for the definition class.

D. Call the start method to start the thread.

Class TestThread extends Thread // a. The definition class inherits the Thread. {Public void run () // B. Rewrite the run method in Thread. {For (int x = 0; x <50; x ++) {System. out. println (Thread. currentThread (). getName () + "...... "+ x) ;}} class Demo {public static void main (String [] args) {TestThread t1 = new TestThread (); // c. Create an instance object for the definition class. TestThread t2 = new TestThread (); t1.start (); // d. Call the start method to start the thread. T2.start ();}}


2. Implement the runnable interface

A. Define the class to implement the Runnable interface.

B. overwrite the run method in the Runnable interface.

C. Create a Thread object through the Thread class.

D. Call the start method to start the thread.

Class TestThread implements Runnable // a. Define the class to implement the Runnable interface. {Public void run () // B. overwrite the run method in the Runnable interface. {For (int x = 0; x <50; x ++) {System. out. println (Thread. currentThread () + "++" + x) ;}} class Demo {public static void main (String [] args) {TestThread d = new TestThread (); Thread t1 = new Thread (d); Thread t2 = new Thread (d); // c. Create a Thread object through the Thread class. T1.start (); // d. Call the start method to start the thread. T2.start ();}}


3. advantages of implementing the Runnable interface

In actual development, we often use the second method for multithreading. Its advantage lies in

A. Avoiding encapsulating tasks into objects according to object-oriented thinking.

B. Avoiding the limitations of java single inheritance.

 

 

 

Ii. Thread Lifecycle

A thread has a life cycle, and its relationships with each life cycle are as follows.

 

 

 

 

Iii. Thread Security

In actual development, there are many scenarios where multithreading is used. For example, in the railway station ticketing system, when multiple threads are used to obtain tickets, if there is only one ticket, one thread will sell the tickets, in this case, the second thread completes the ticket determination and reaches the conclusion that the number of votes is greater than 0. At this time, the ticket sales will generate a negative number.

1. Causes of security problems

A. Multiple Threads are manipulating shared data.

B. There are multiple codes for manipulating shared data.

2. solution-synchronization

Encapsulate the thread code of multiple operations that share data. When a thread executes the Code, other threads cannot participate.

A. synchronous code block


Synchronized (obj) {// code to be synchronized}

B. synchronous Functions

Public synchronized void show () {// code to be synchronized}


3. Differences between synchronous functions and synchronous code blocks

The lock of the synchronous function is this

The lock of the synchronized code block is arbitrary (or this can be used)

We recommend that you use synchronous code blocks during actual development.

4. Advantages and Disadvantages of Synchronization

Benefit: it solves the security problem of multithreading.

Disadvantages: multiple threads need to judge the lock, which consumes more resources.

5. Static function code block

What is the lock used after the synchronization function is statically modified? The Singleton mode in the design mode is shown to you.

// Lazy class Single {private static Single s = null; private Single () {} public static Single getInstance () {if (s = null) {synchronized (Single. class) // write the static method --- class name. class {if (s = null) s = new Single () ;}} return s ;}}


4. Inter-thread Communication

Inter-thread communication means that multiple threads share the same resource.

Class ResorceDemo {public static void main (String [] args) {Resorce r = new Resorce (); Input in = new Input (r); Output out = new Output (r ); thread t1 = new Thread (in); Thread t2 = new Thread (out); t1.start (); t2.start () ;}} class Resorce // define a resource {String name; string sex; boolean flag = false;} class Input implements Runnable // write resource {Resorce r; Input (Resorce r) {this. r = r;} public void run () // re-write run method {int x = 0; // x is equivalent to a flag. while (true) {synchronized (r) {if (r. flag = true) {try {r. wait ();} catch (InterruptedException e) {}} else {if (x = 0) {r. name = "mike"; r. sex = "nan";} else {r. name = "silly girl"; r. sex = "niu Niu I Niu ii niu";} r. flag = true; r. Y (); // wake up} x = (x + 1) % 2; // x alternate between 0 and 1 .}}}} class Output implements Runnable // read resource {Resorce r; Output (Resorce r) {this. r = r;} public void run () {while (true) // infinite loop {synchronized (r) {if (r. flag = false) {try {r. wait ();} catch (InterruptedException e) {}} else {System. out. println (r. name + "... "+ r. sex); r. flag = false; r. notify ();}}}}}


5. Common Operations

1. wait (): The thread is frozen, and the thread that is wait will be stored in the thread pool.
2, Y (): Wake up a thread (any) in the thread pool ).
3. yyall (): Wake up all threads in the thread pool.
4, setPriority (): set priority
5. yield (): Pause the current thread for other threads to execute.

 

Of course, these common operation methods can be found in the API. This is not the point I want to talk about. Here we will compare these methods.

 

(1) What is the difference between wait and sleep?

1. wait can be specified or not. Sleep must specify the time.

2. During synchronization, the cpu's execution right and lock are handled differently. Wait: Release the execution right and release the lock. Sleep: Release the execution right without releasing the lock.

(2) Why is the thread defined in the Object class?

A. These methods exist and are being synchronized.

B. When using these methods, you must identify the synchronization lock to which it belongs. The same wait lock thread can only be awakened by the notify of the same lock.

C. The lock can be any Object. Therefore, the method called by any Object must be defined in the Object class.

Vi. Summary

Multithreading itself is also a complicated problem. It still takes time to fully understand it. The so-called attention can be a coincidence. This knowledge can only be truly mastered through more practical practices.

 

 

 

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.