Black Horse Programmer-java-based multi-threading

Source: Internet
Author: User
Tags closing tag thread stop ticket

Multithreading

Process : A program that is in progress. In fact, a process is a memory allocation space when an application runs.

thread : It is actually a program execution control unit in the process, an execution path. The process is responsible for the application's spatial labeling. Threads are responsible for the order in which the application executes.

A process has at least one thread running, and when multiple threads appear in a process, the application is called a multithreaded application, and each thread has its own execution space, its own method area, and its own variables in the stack area.

When the JVM starts, it first has a main thread, which is responsible for the execution of the program, and the main function is called. The code executed by the main thread is in the main method.

When garbage is generated, the garbage collection action is not required to complete the main thread, because in this case, the code execution in the main thread will stop, will run the garbage collector code, inefficient, so a separate thread responsible for garbage collection.

the principle of randomness : Because of the rapid switchover of the CPU, which thread gets the execution of the CPU and which thread executes it.

Returns the name of the current thread:thread.currentthread (). GetName ()

The name of the thread is defined by the: thread-number. Numbering starts from 0.

The code that the thread wants to run is stored uniformly in the run method .

The thread must be run by using the method specified in the class. Start Method . (after startup, one more execution path)

Start method:1), start the thread, 2), let the JVM call the Run method.

The first way to create a thread is to inherit the thread, which is a subclass of the Run method.

Steps:

1, the definition class inherits the thread class;

2, the purpose is to copy the Run method, the code that will let the thread run is stored in the Run method;

3, create a thread object by creating a subclass object of the thread class;

4, call the thread's Start method, open the thread, and execute the Run method.

Thread State:

created by:start ()

operation: qualified for execution, with execution right;

Freeze:Sleep (time), wait ()-notify () Wake up, thread releases execution, and release execution eligibility;

temporary blocking state: The thread has the CPU's execution qualification, no CPU execution right;

Extinction:Stop ()

The second way to create a thread: Implement an interface runnable.

Steps:

1, defines the class implementation runnable interface.

2, overwrite the Run method in the interface (used to encapsulate the code that the thread is running).

3, the thread object is created through the thread class;

4, the subclass object that implements the Runnable interface is passed as the actual parameter to the constructor in the thread class.

Why should it be passed? Because you want the thread object to explicitly run the object that the Run method belongs to.

5, call the Start method of the Thread object. Open the thread and run the running method in the Runnable interface subclass.

Ticket t = new Ticket ();

Thread t1 = new Thread (t); //Create thread.

T1.start ();

Why should there be a runnable interface?

1 : The creation of multithreading can be accomplished by inheriting the thread class. However, this approach has a limitation, if a class already has its own parent class, it is not possible to inherit the thread class because of the limitations of Java single inheritance.

However, some of the code in this class needs to be executed concurrently by multiple threads. What then?

Java provides an interface runnable only if additional functionality is extended to the class. The Run method is defined in this interface, in fact the definition of the Run method is to store code that is multithreaded to run.

Therefore, it is common to create threads in a second way.

Because implementing the Runnable interface avoids the limitations of single inheritance.

2 : In fact, it is not the same kind of code that needs to be multithreaded execution. Define the location of the code that is multithreaded to run separately into the interface. Provides the prerequisites for extending the functionality of other classes.

So when the thread class describes threads, the internally defined run method is also derived from the Runnable interface.

implementing the Runnable interface avoids the limitations of single inheritance. also, inheriting thread, you can make a subclass of the method in the thread class. However, it is more convenient to implement the Runnable interface just to define the location of the thread code, without the need for this replication action. So the Runnable interface encapsulates the task that the thread is performing as an object .

-------------------------------------------------------

// Interview

New Thread (new Runnable () { //anonymous

Public void Run () {

System.out.println ("runnable run");

 }

 })

 {

Public void Run () {

System.out.println ("Subthread run");

 }

}.start (); // Result: Subthread run

---------------------------------------------------------

Try {

Thread.Sleep (10);

}catch (Interruptedexception e) {}// when the thread is deliberately paused, simulate the CPU switchover situation.

reasons for Multithreading security issues :

By illustration: When a thread executes multiple statements and the same data is executed, other threads participate in the process and manipulate the data. result in the creation of the wrong data.

Two factors are involved:

1 , multiple threads are manipulating the shared data.

2 , there are multiple statements that perform operations on the shared data.

Cause: These multiple statements are executed by another thread at some point when they are executed by a thread and have not finished executing.

How to solve the security problem :

As long as the statement that the operation shares data has been executed by a thread during a certain period of time, it can be resolved by other threads that cannot come in during execution.

How to do multi-sentence operation shared data code encapsulation?

Java provides a workaround: synchronization of code blocks.

Format:

synchronized ( object) { // any object can be. This object is the lock.

code that needs to be synchronized;

}

---------------------------------------------------------------

Sync: ★★★★★

benefit: resolves a thread safety issue.

cons : Relatively low performance because the lock needs to consume resources, resulting in deadlocks.

There are prerequisites for defining synchronization :

1, must have two or more than two threads, only need to synchronize.

2, multiple threads must be guaranteed to use the same lock.

The second manifestation of synchronization:

synchronization function : In fact, the synchronization keyword is defined on the function, so that the function has synchronization.

Which lock does the synchronization function use?

By verifying that the function has its own object this, the lock used by the synchronization function is the this lock .

When the synchronization function is modified by static, which lock is used for synchronization?

The static function belongs to the class at the time of loading, and it is possible that the object is not produced by the class, but the bytecode file of the class is loaded into the memory and has been encapsulated as an object, which is the bytecode file object of the class .

So when static loading, only one object exists, then the static synchronization function uses this object.

This object is the class name. Class

What is the difference between a synchronous code block and a synchronization function?

The lock used by the synchronization 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 the class .

There is only one synchronization in a class, and you can use synchronous functions. If you have multiple synchronizations, you must use a synchronous code block to determine the different locks. So the synchronization code block is relatively flexible.

-------------------------------------------------------

★ Test Center PROBLEM: Please write a lazy load of the singleton mode? Write lazy-style; how to solve when multi-threaded access occurs? To solve security problems and high efficiency? Not high; how to solve? Resolved in the form of double judgments.

Lazy type: Lazy loading mode.

When multi-threaded access to lazy-type, because of the lazy way of the common data in the operation of multiple statements. So it's easy to have thread safety issues. In order to solve, join the synchronization mechanism to solve security problems. But it has brought about a decrease in efficiency.

In order to solve the problem of efficiency, it is solved by double judgment.

Class single{

private static single s = null;

Private single () {}

Public Static Single getinstance () {/// lock is who? Byte-code file object;

if (s = = null) {

synchronized (single.class) {

if (s = = null)

s = new single ();

 }

 }

return s;

 }

}

---------------------------------------------------------

Synchronous Deadlocks : You can usually see the phenomenon as long as the synchronization is nested. There is a synchronous code block in the synchronization function, and a synchronization function in the synchronization code block.

inter-thread communication : Ideas: Multiple threads are manipulating the same resource, but the action is different.

1: Encapsulates the resource as an object.

2: The task that the thread performs (the task is actually the Run method.) ) is also encapsulated as an object.

wait for wake-up mechanism: The method involved:

wait: The thread in the synchronization is frozen. Release the executive right and release the eligibility. Store thread objects in the thread pool at the same time.

Notify : wakes one of the waiting threads in the thread pool.

Notifyall: All threads in the thread pool are awakened.

Attention:

1: These methods need to be defined in synchronization.

2: Because these methods must be marked to belong to the lock.

you have to know that the thread of a lock is wait, and that this thread is equal to the thread pool in a lock, only the notify of a lock can wake up.

3: All three of these methods are defined in the object class. Why is the method definition of an action thread in the object class?

because these three methods all need to define the synchronization, and to identify the synchronization lock belongs to, since the lock is called, and the lock can be any object, the method can be called by any object must be defined in the object class.

wait and sleep differences: analyze these two methods: from the executive right and the lock to analyze:

Wait: You can specify a time or you can not specify a time. No time is specified and can only be awakened by the corresponding notify or Notifyall.

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

wait : Threads release execution, and threads release locks.

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

thread Stop: The thread can be stopped by means of the Stop method. But this way is out of date.

Stop thread: The principle is: let the thread run the code end, that is, the end of the Run method.

How do I end the Run method? The general Run method definitely defines loops. So just end the loop.

The first way: define the closing tag for the loop.

The second way: if the thread is in a frozen state, it is impossible to read the tag, then it needs to be forced to clear its frozen state through the interrupt method in the thread class. Let the thread recover the status of the execution qualification, so that the thread can read the tag and end.

---------< Java.lang.Thread >----------

Interrupt () : medium Break thread.

setpriority (int newpriority) : Change the priority of a thread.

getpriority () : Returns the priority of the thread.

toString () : Returns the string representation of the thread, including the thread name, priority, and thread group.

Thread.yield () : pauses the currently executing thread object and executes other threads.

Setdaemon (True) : marks the thread as either a daemon thread or a user thread. Mark the thread as either a daemon thread or a user thread. When a running thread is a daemon thread, the Java virtual machine exits. The method must be called before the thread is started.

Join: You can use the Join method when you temporarily join a thread.

When a thread executes the Join method to the B thread. A thread is in a frozen state, releasing execution and B starting execution. A when will it be executed? Only when the B thread has finished running does the a resume running state from the frozen state.

-----------------------------------------------------------

Lock Interface: multithreaded when upgrading the JDK1.5 version, an interface lock interface is introduced.

The solution to thread safety is to use synchronous form, (synchronous code block, or synchronous function) in fact, the ultimate use of the lock mechanism.

To a later version, the lock is directly encapsulated as an object. The thread enters the synchronization is has the lock, executes, leaves the synchronization, is releases the lock.

During the later analysis of the lock, it was found that acquiring the lock, or releasing the lock, should be more clear about the lock thing. So these actions are defined in the lock, and the lock is defined as an object.

So synchronization is an implicit lock operation, and the lock object is a displayed lock operation , and its appearance replaces synchronization.

This was done in previous versions using Wait, notify, Notifyall in the object class. That is because the locks in the synchronization are arbitrary objects, so the method of waiting for the operation lock is defined in the object class.

And now the lock is the specified object lock. So the way to find a wait-and-wake mechanism is done through the lock interface. In the lock interface, there is no direct manipulation of the method waiting to be awakened, but these methods are encapsulated separately into an object. This object is Condition, which encapsulates the three methods in the object in a separate package. and provides a functionally consistent approach to await (), signal (), Signalall () to embody the benefits of the new version object.

< java.util.concurrent.locks > Condition interface:await (), Signal (), Signalall ();

--------------------------------------------------------

Class Boundedbuffer {

Final Lock lock = new Reentrantlock ();

final Condition notfull = lock.newcondition ();

final Condition notempty = lock.newcondition ();

final object[] items = new object[100];

int putptr, takeptr, Count;

Public void put (Object x) throws Interruptedexception {

Lock.lock ();

try {

While (count = = items.length)

notfull.await ();

items[putptr] = x;

if (++putptr = = items.length) putptr = 0;

++count;

notempty.signal ();

 }

finally {

Lock.unlock ();

 }

 }

Public Object Take () throws Interruptedexception {

Lock.lock ();

try {

While (count = = 0)

notempty.await ();

Object x = items[takeptr];

if (++takeptr = = items.length) takeptr = 0;

--count;

notfull.signal ();

return x;

 }

finally {

Lock.unlock ();

 }

 }

Black Horse Programmer-java-based multi-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.