Dark Horse Programmer -- java basics -- multithreading, dark horse programmer java

Source: Internet
Author: User

Dark Horse Programmer -- java basics -- multithreading, dark horse programmer java
Zookeeper

Dark Horse programmers -- java basics -- Multithreading

------ Java training, Android training, iOS training, and. Net training. We look forward to communicating with you! -------

Process: A program in progress. Each process has an execution order. This sequence is an execution path or a control unit.
Thread: an independent control unit in a process. The thread is controlling the execution of the process. A process has at least one thread.

A process must have at least one thread running. When multiple threads exist in a process, this application is called a multi-threaded application, each thread has its own execution space, its own method zone, and its own variables in the stack zone.

When jvm is started, there isMain threadAnd is responsible for program execution. The main function is called. The Code executed by the main thread is in the main method.

When garbage collection is generated, the garbage collection action does not need to be completed by the main thread. As a result, code execution in the main thread will stop and the garbage collector code will be run, low efficiency, so a separate thread is responsible for garbage collection.
Extension: in fact, more details about jvm: jvm starts more than one thread, and there are also threads responsible for the garbage collection mechanism.

Principles of randomness: Because of the fast cpu switching, which thread gets the cpu execution right will be executed.


Returns the name of the current Thread: Thread. currentThread (). getName ()

The Thread name is defined by: Thread-number. The number starts from 0.

The code to be run by the thread is stored in the run method.

To run a thread, it must be enabled through the method specified in the class. Start method. (After startup, an execution path is added)

Start method: 1). The thread is started; 2) the jvm calls the run method.

Thread Creation Method

There are two ways to create a thread: inheritance and implementation.

The first way to create a Thread: Inherit the Thread and rewrite the run method by the subclass.

Steps:

1. The definition class inherits the Thread class;

2. The purpose is to re-write the run method and store the code to run by the thread in the run method;

3. Create a Thread object by creating a subclass object of the Thread class;

4. Call the start method of the thread, enable the thread, and execute the run method.

Class MyThread extends Thread {public MyThread () {super (); // TODO Auto-generated constructor stub} public MyThread (String name) {super (name ); // TODO Auto-generated constructor stub} public void run () {for (int I = 0; I <10; I ++) {System. out. println ("Demo:" + Thread. currentThread (). getName () + ":" + I) ;}} public class ThreadDemo {public static void main (String [] args) {// TODO Auto-generated method stubMyThread demo1 = new MyThread ("thread 1"); demo1.start (); MyThread demo2 = new MyThread ("thread 2"); demo2.start (); for (int I = 0; I <10; I ++) {System. out. println ("main:" + I );}}}

Method 2 for thread creation: Implement an interface Runnable

Steps:

1. Define the class to implement the Runnable interface.

2. overwrite the run method in the interface (used to encapsulate the code to be run by the thread ).

3. Create a Thread object through the Thread class;

4. Pass the subclass object that implements the Runnable interface to the constructor In the Thread class as an actual parameter.

Why? The reason is that the thread object must be clear about the object to which the run method belongs.

5. Call the start method of the Thread object. Enable the thread and run the run method in the Runnable interface subclass.

Class Ticket implements Runnable {private int tick = 100; public void run () {while (true) {if (tick> 0) {System. out. println (Thread. currentThread (). getName () + ".... sale: "+ tick --) ;}}} class TicketDemo {public static void main (String [] args) {Ticket t = new Ticket (); thread t1 = new Thread (t); // creates a Thread; Thread t2 = new Thread (t); // creates a Thread; t1.start (); t2.start ();}}

Why does the Runnable interface appear?

1: The establishment of multiple threads can be completed by inheriting the Thread class. However, this method has a limitation. If a class already has its own parent class, it cannot inherit the Thread class because of the limitation of java single inheritance.

However, some code in this class needs to be executed by multiple threads at the same time. What should we do?

Java provides an interface Runnable only for additional function extensions of this class. This interface defines the run method. In fact, the run method is defined to store the code to be run by multiple threads.

Therefore, the second method is usually used to create a thread.

The Runnable interface can avoid the limitation of single inheritance.

2: extract the code that needs to be executed by multiple threads in different classes. Define the location of the Code to be run in multiple threads to an interface. It provides a prerequisite for other classes to Expand functions.

So when the Thread class describes a Thread, the internally defined run method also comes from the Runnable interface.

Implementing the Runnable interface can avoid the limitation of single inheritance. In addition, inheriting the Thread class can be used to perform subclass rewriting on the methods in the Thread class. However, if you do not need to perform this rewrite operation, you only need to define the location where the thread code is stored, making it easier to implement the Runnable interface. Therefore, the Runnable interface encapsulates the tasks to be executed by the thread into objects.

Thread status:

Created: start ()

Run: qualified for execution and the execution right;

Freeze: sleep (time), wait ()-y () Wake up; the thread releases the execution permission and releases the execution qualification;

Temporary blocking status: the thread is qualified to execute cpu, and has no execution right of cpu;

Extinction: stop ()


Thread security issues

Reasons for multithreading security problems:
Illustration: When a thread executes multiple statements and computes the same data, other threads participate in the execution and operate the data. The error data is generated.

There are two factors involved:
1. multiple threads share data during operations.
2. There are multiple statements to calculate the shared data.
Cause: when these statements are executed by one thread at a certain time point, they are executed by other threads.
Principles for solving security problems:
As long as the statement for sharing data operations is completed by a thread in a certain period of time, other threads cannot come in for execution during the execution process to solve this problem.

Java provides a professional solution to multi-thread security issues-synchronized)

There are also two solutions: Synchronous Code blocks and synchronous functions. All are implemented using the keyword synchronized.

A. synchronous code block

Usage:

Synchronized (object)

{Code to be synchronized}

The root cause of security problems solved by synchronization is on that object. The object is like a lock. The thread holding the lock can be executed in synchronization. The thread that does not hold the lock cannot even obtain the execution right of the cpu, because the lock is not obtained.

<span style="font-size:14px;">class Ticket implements Runnable{private  int tick = 1000;Object obj = new Object();public void run(){while(true){synchronized(obj){if(tick>0){//try{Thread.sleep(10);}catch(Exception e){}System.out.println(Thread.currentThread().getName()+"....sale : "+ tick--);}}}}}class  TicketDemo2{public static void main(String[] args) {Ticket t = new Ticket();Thread t1 = new Thread(t);Thread t2 = new Thread(t);t1.start();t2.start();}}</span>

B. synchronous Functions

In fact, the synchronous keywords are defined on the function, so that the function can be synchronized.

Which lock is used for Synchronous functions?

After verification, the function has its own object this, so the lock used by the synchronous function is the this lock.

<span style="font-size:14px;">class Ticket implements Runnable{private  int tick = 100;Object obj = new Object();boolean flag = true;public  void run(){if(flag){while(true){show();}}}public synchronized void show()//this{if(tick>0){try{Thread.sleep(10);}catch(Exception e){}System.out.println(Thread.currentThread().getName()+"....show.... : "+ tick--);}}}class  ThisLockDemo{public static void main(String[] args) {Ticket t = new Ticket();Thread t1 = new Thread(t);t1.start();}</span>

Which lock is used for synchronization when the synchronization function is modified statically?

Static functions belong to the class when they are loaded. At this time, there may not be any objects generated by this class, but the bytecode files of this class have been encapsulated into the memory, this object is the bytecode object of this class.

So only one object exists during static loading, so this object is used by the static synchronization function.

This object is the class name. class

class Single{private static Single s = null;private Single(){}public static  Single getInstance(){if(s==null){synchronized(Single.class){if(s==null)//--->A;s = new Single();}}return s;}}class SingleDemo {public static void main(String[] args) {System.out.println("Hello World!");}}

Differences between Synchronous Code blocks and synchronous Functions

The lock used by the synchronous code block can be any object.

The lock used by the synchronization function is this, and the lock of the static synchronization function is the bytecode file object of this class.

Advantages and disadvantages of Thread Synchronization

Benefits: solved thread security issues.

Disadvantage: relatively low performance, because the lock consumes resources, resulting in a deadlock.

There are prerequisites for defining synchronization:

1. synchronization is required only when two or more threads exist.

2. Multiple Threads must use the same lock.

Synchronization deadlock

We can see the phenomenon as long as synchronization is nested. Synchronous functions include Synchronous Code blocks and synchronous functions.


public class DeadLockDemo {public static void main(String[] args) {// TODO Auto-generated method stub// TODO Auto-generated method stubTicket1 ticket1 = new Ticket1();Thread thread1 = new Thread(ticket1);thread1.start();try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}Thread thread2 = new Thread(ticket1);ticket1.flag = false;thread2.start();}}class Ticket1 implements Runnable{private static int ticket1 = 10;private Object obj = new Object();boolean flag = true;@Overridepublic void run() {// TODO Auto-generated method stubif(flag){while(true){synchronized (obj) {show();}}}else{while(true){show();}}}public synchronized void show(){synchronized (obj) {if(ticket1>0){try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println(Thread.currentThread().getName()+":"+ticket1--);}}}}

Inter-thread communication:
In fact, multiple threads operate on the same resource, but the operations are different.

1: encapsulate resources into objects.

2: tasks executed by the thread (the task is actually the run method .) It is also encapsulated into an object.

<Span style = "font-size: 14px;"> class Res {String name; String sex; boolean flag = false;} class Input implements Runnable {private Res r; input (Res r) {this. r = r;} public void run () {int x = 0; while (true) {synchronized (r) {if (r. flag) try {r. wait () ;}catch (Exception e) {}if (x = 0) {r. name = "mike"; r. sex = "man";} else {r. name = "Lili"; r. sex = "female";} x = (x + 1) % 2; r. flag = true; r. notify () ;}}} class Output implements Runnable {priv Ate Res r; Output (Res r) {this. r = r;} public void run () {while (true) {synchronized (r) {if (! R. flag) try {r. wait ();} catch (Exception e) {} System. out. println (r. name + ".... "+ r. sex); r. flag = false; r. notify () ;}}} class InputOutputDemo {public static void main (String [] args) {Res r = new Res (); Input in = new Input (r ); output out = new Output (r); Thread t1 = new Thread (in); Thread t2 = new Thread (out); t1.start (); t2.start ();}} </span>

Wait for wake-up Mechanism

Methods involved:

Wait: the synchronization thread is frozen. The execution right is released and the qualification is released. At the same time, the thread object is stored in the thread pool.

Wake Y: Wake up a waiting thread in the thread pool.

Yyall: Wake up all threads in the thread pool

Note:

1: these methods must be defined in synchronization.

2: because these methods must mark the lock.

You need to know that the thread locked by A is wait, then this thread is equivalent to being in the thread pool of lock A and can only wake up with the slave y of lock.

3: all three methods are defined in the Object class. Why is the method of the Operation thread defined in the Object class?

Because all three methods need to define the synchronization and mark the synchronization lock to which they belong, since the lock is called, and the lock can be any object, the methods that can be called by any Object must be defined in the Object class.

Differences between wait and sleep:

Analysis of these two methods: From the execution right and lock analysis:

Wait: either time or time is specified. If no time is specified, it can only be awakened by the corresponding y or notifyAll.

Sleep: the time must be specified to automatically change from frozen to running (temporary blocking ).

Wait: the thread releases the execution permission and the thread releases the lock.

Sleep: the thread releases the execution permission but does not release the lock.














Zookeeper

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.