Java Multithreaded Example

Source: Internet
Author: User

Here we do a complete sample of the threads that are generated in different ways by the thread:

Package debug;

Import java.io.*;
Import Java.lang.Thread;


Class MyThread extends thread{
public int x = 0;

public void Run () {
System.out.println (++X);
}
}

Class R implements runnable{
private int x = 0;
public void Run () {
System.out.println (++X);
}
}

public class Test {
public static void Main (string[] args) throws exception{

for (int i=0;i<10;i++) {
Thread t = new MyThread ();
T.start ();
}
Thread.Sleep (10000);//allow the above thread to finish executing
R r = new R ();
for (int i=0;i<10;i++) {
Thread t = new Thread (r);
T.start ();
}
}
}

The 10 threads generated by the above 10 thread objects were printed 10 times 1 when executed. The following 10 thread objects produced by 10 threads are executed with 1 to 10 printed. We refer to the following 10 threads as multiple threads of the same instance (runnable instance) .

In the next section we will look at the thread object method, or the sentence that can be read in the general document I will not introduce too much
Please let us know.

A few important methods of threading objects

Although the regular usage of thread objects can be understood through API documentation, there are a number of methods that are not specifically understood from API descriptions.

Originally intended to use a section of the thread approach to some of the important knowledge, but this is expected to be a non-regular space, may have to use a number of skills to say and threading methods related to some important knowledge to finish.

First, we take the basic article (ii) to illustrate the start () method.

After a thread object is generated, it is assumed that to produce a running thread, it is necessary to invoke its start () method. This method has to be described at the same time as the Run method. In fact, the run method of the thread object is completely an interface callback method. It is the detailed logic that you are going to complete with this thread object. Simply say what you're going to do, and you're done in run, and when you do, you don't have to control it, you just call the start () method, and the JVM manages the thread object to generate a thread and register it with the threading system.

On the surface, the start () method calls the run () method, in fact, the start () method does not directly call the Run method. In JDK1.5 once the start () method is the local method, How it finally calls the Run method is not something that the Java program Ape can understand. In JDK1.5, the original local start () method is replaced by Start0 (), and another pure Java start () calls the Local method Start0 (), while the start () The method verifies that a global variable (object variable) started is checked, assuming true, start () throws an exception, the Local method Start0 () is not called, otherwise the variable is first set to true and then called Start0 ().

From which we can see this in order to control a thread object can only perform a successful start () method. This is because the thread executes to get the current environment, contains security, permissions for the parent thread, precedence, and so on, assuming that a thread object can execute multiple times, then define a static Thread gets the corresponding permission and priority in an environment, it executes in the current environment with attributes such as permissions and precedence in an environment, which can result in unpredictable results. In short, having a thread object execute only once is based on the need for thread management.

The most essential function of the start () method is to request a thread space from the CPU to execute the code in the Run () method, which is two lines from the current thread and executes in a relatively separate thread space, that is, assuming that you directly invoke the run () method of the Thread object, and of course it does, but that is Executes in the current thread, and executes the following code after execution of the run () method. When the start () method is called, the Code of the Run () method executes concurrently (single CPU) or parallel (multi-CPU) with the current thread.

So remember a word [the Run method that invokes the thread object does not produce a new thread], although the same result can be achieved, the running process and the efficiency of the operation are different.

[Thread's Interrupt () method, Interrupted () and isinterrupted ()]

These three methods are very close and complex, though their respective functions are very clear, but the relationship between them is not really understood by most people.

First say the interrupt () method, which is an instance method, and it is also the strangest way, in the Java language, the thread was originally designed to be "obscure", until now its semantics are not as accurate as its name. Most people think that a thread called the Interrupt () method, then its corresponding thread should be interrupted and throw an exception, in fact, when a thread object calls the interrupt () method, its corresponding thread is not interrupted, just changed its interrupt state.

Changes the state of the current thread to a break state, assuming that there are no other effects, the thread will continue to run itself.

The thread throws an exception only if the thread is running to a method such as Sleep,wait,join, or if it throws an exception by checking the interrupt state itself.

Assuming that the thread object calls interrupt () and its corresponding thread is interrupted immediately, the interrupted () method cannot run.

Since the interrupted () method is a static method, which means it can only be called on the current thread, and if it has been interrupted after a thread interrupt (), how does it let itself interrupted ()?

Just because a thread calls interrupt () but changes the interrupt state, it can continue to run, and it can call interrupted () to clear the interrupt state (as it is) before calling Sleep,wait,join or throwing an exception by itself. The interrupted () method checks the interrupt state of the current thread, assuming that the "interrupted state" changes the current thread to "non-disruptive state" and returns true, assuming that the "non-disruptive state" returns false, which not only checks whether the current thread is in a broken state, but also guarantees that when The front-end is returned in a non-interruptible state, so it's called "interrupted", which means that the state of the interrupt has ended (to a non-interruptible state) The isinterrupted () method only checks that the thread object's corresponding thread is in a broken state and does not change its state.

Now you can only remember the functions of these three methods, only really deep into the practice of multi-threaded programming, you will understand why they are object methods, why is the class method.

Exactly when the thread was interrupted to throw the interruptedexception exception, we will discuss it in detail in the improvement article.

[Sleep (), join (), yield () method]

In today's session, I can only explain the role of these methods and the principle of invocation, as to why, in the basic article can not be in-depth, only in the improvement of the specific description.

The sleep () method is a class method, that is, for the current thread, the program ape cannot specify a thread to sleep, but only when the current thread executes to the sleep () method, the time that is specified by the sleep (for other threads to execute). In fact, it can only be a class method, Called on the current thread. Imagine that if you invoke the sleep () method of a thread object, how does it sleep () if the corresponding thread of the object is not executing? So there is only the current thread, and because it is executing, you can guarantee that it will be able to invoke the sleep () method.

Principle: [Try not to invoke the sleep () method of the thread in the synchronization method], or simply say that you should not call the sleep () method for the general level of the program ape.

Join () method, as described in the first section, calls the Join method on a thread object, which is the current thread that waits for the thread object to end, for example, two jobs, work a takes 10 seconds, work B takes 10 seconds or many others. We're in the program Mr. A thread goes to work B and then does a.

New? B (). Start ();//Work B

A ();//Work A

After work A is finished, wait for the result of work B to be processed. Assuming work B is not finished, I can't do the following work C, so

B?b?=?new? B ();

B.start ();//Work B

A ();//Work A

B.join ();//wait for work B to finish.

C ();//continue to work C.

Principle: [Join is the only correct way to test other work states], I have seen a lot of people, even PhD students, in the process of a job is assumed to have a work not finished, said to let the current work thread sleep (x), I asked him, you this x is how to specify, How do you know it's 100 milliseconds instead of 99 milliseconds or 101 milliseconds? In fact, this is the essence of the OnXxx event, and we do not have to wait much longer to do something, but to do it when the waiting work is finished.

The yield () method is also a class method that is invoked only on the current thread, as in the case where the main reason is to let the current thread discard the time slice principle assigned to it: [Not necessary, there is no reason to invoke it]. Calling this method does not improve efficiency, Just to reduce the total cycle time of the CPU some of the methods described above are simply mentioned in terms of (basic). In the future, I will combine practical examples to discuss the specific application.

Other methods of threading itself refer to the API documentation. The next section describes a non-threading approach, but two [three] object methods that are closely related to threads:

[Wait (), notify ()/notifyall ()]

This is a very important method in multi-threading.

There is a lot to be said about these two methods. There may be a great many places in the following notes that cannot be clarified at once, but after reading this section, even if it is not entirely clear, you must return to remember the following two words:

  [Wait (), the Notify ()/notityall () method is a method of a normal object (implemented in an object superclass), not a method of a thread object]

  [Wait (), the Notify ()/notityall () method can only be called in the synchronous method]

[Thread's mutual exclusion control]

When multiple threads manipulate an object at the same time, the operation of a thread on that object may change its state, and that state affects the actual result of the process on that object.

We can see this example in too many documents, just like two conductors selling the same ticket at the same time.

Thread A thread B
1. Thread A queries the database for deposit tickets and finds that the ticket C can be sold
Class= "left" 2. Thread a accepts the user's booking request and prepares the ticket.
3. Then switch to thread B run
4. Thread B queries the database for deposit tickets and finds that the ticket C can be sold
5. Thread B sold out the tickets.
6. Switch to thread A to run, thread a sells a ticket that has been sold

So a mechanism is needed to manage this kind of problem, and when a thread is running a non-cutting part, other threads cannot run this part at the same time.

A mechanism like this that controls just one thread at a time to run a single running unit is called mutual exclusion control or shared mutual exclusion (mutual exclusion)

In Java, Synchornizedkeyword is used to achieve mutual exclusion control (temporarily, JDK1.5 has developed a new mechanism)

[Synchornizedkeyword]

Declaring a unit as synchornized allows the method to be manipulated by just one thread at a time.

Some people say that synchornized is a lock, in fact, it does exist lock, but who is the lock, lock who, this is a very complex problem.

Each object has only one monitoring lock (monitor lock), which can only be acquired by one thread at a time. When a thread acquires this lock, the other threads can just wait for the thread to release the lock talent and retrieve it.

So, what exactly is Synchornizedkeyword locked up? Who's got the lock?

For a synchronization block, synchornized gets the object lock in the parameter:

Synchornized (obj) {
//...............
}

When a thread runs here, the first thing to get is the lock on the instance of obj, assuming that no thread can wait. Assuming that multiple threads are running here, only one thread can get the lock of obj and then run the statements in {}, so the Obj object has different scopes and different control programs.

If:

public void Test () {
Object o = new Object ();

Synchornized (obj) {
//...............
}
}

This section controls no matter what, multiple threads run to object o = new Object (), each resulting in an object and then acquiring the object has a monitoring lock, each running happily.

The assumption is that the properties of the class are:

Class test{
Object o = new Object ();
public void Test () {

Synchornized (o) {
//...............
}
}
}

All running to the synchornized (o) thread of the test instance, only one thread is able to acquire a monitoring lock.

Sometimes we do this:

public void Test () {

Synchornized (This) {
//...............
}
}

Then all the threads running the test instance can only have one thread running. The range of synchornized (O) and synchornized (this) is different, because the thread that runs to the test instance's synchornized (O) Waits. Other threads can run the synchornized (O1) portion of the test instance, but multiple threads have only one synchornized (this) that can run the test instance at the same time.

And for

Synchornized (Test.class) {
//...............
}

For this synchronization block, all threads that call test multiple instances can only have one thread to run.

[Synchornized Method]

Assuming that a method is declared as synchornized, it is equivalent to calling synchornized (this) on a method.

Assuming a static method is declared as synchornized, it is equivalent to calling Synchornized (class. Classes) on a method.

Now enter the wait method and the Notify/notifyall method. These two (or three) methods are methods of object objects, not methods of thread objects. Like locks, they are run on an object that is called on an inline thread.

Class test{
Public synchornized Void Test () {
Get condition, int x requires greater than 100;

if (x < 100)
Wait ();
}
}

In order to illustrate that the method is not added to Try{}catch () {}, it is this.wait () if it is not understood on which object the wait () method is called;

If:

Test T = new Test ();

There are now two threads running to T.test (); in which thread a acquires the object lock of T and enters the test () method.

At this point x is less than 100, so thread a enters the wait.

When a thread calls the wait method, the thread enters the object's Rest room (Waitset), which is a dummy object, but there must be a data structure in the JVM that records which threads in the current object are waiting.

When a thread enters the wait, it releases the lock and lets the other thread get the lock.

So thread B has a chance to get a lock released by thread A, into the test () method, assuming that at this point the X is still less than 100, and thread B enters the t's Rest room.

These two threads can only be awakened by waiting for other threads to invoke Notity[all].

However, assuming that the call is a reference to the wait (time) method, then the thread A, B, will wait for this time in the rest room to wake up voluntarily.

[Why real applications are using while (conditions) without the IF (condition)]

In the actual programming we see a large number of examples are used?

while (x < 100)

Wait (); Go (); instead of using if, why?

If multiple threads are running at the same time, if (X-<100) is unsafe. Since it is assumed that thread A and thread B are waiting in the rest room of T, there is a thread that makes x==100 and calls the Notifyall method, and thread A continues to run the following go (). And when it's finished running, X may be less than 100, for example, the following program calls the--x, then switch to thread B, thread B does not continue to infer, directly run go (); A wrong condition is created, and only the while talent guarantees that thread B continues to check again.

[Notify/notifyall Method]

Both of these methods wake up a thread in the resting area of an object, and notify only wakes one, but the Notifyall wakes up all the threads in the rest room on the object.

Generally for security, we should use Notifiall () in absolute majority, unless you understand that only one thread is awakened.

So is it just to invoke the wait () method of an object and the current thread enters the object's rest room? In fact, to invoke the Wait () method of an object, only the current thread acquires the lock of the object. In other words, be sure to synchronize with this object or in a synchronized block with this object as the parameter.

Class MyThread extends thread{
Test T = new Test ();
public void Run () {
T.test ();
System.out.println ("Thread say:hello,world!");
}
}

public class Test {

int x = 0;
Public Void Test () {
if (x==0)
try{
Wait ();
}catch (Exception e) {}
}
public static void Main (string[] args) throws exception{
New MyThread (). Start ();
}
}

This thread will not enter the T wait method and print out the thread say:hello,world! directly.

And the hypothesis is changed into:

public class Test {

int x = 0;
Public synchornized Void Test () {
if (x==0)
try{
Wait ();
}catch (Exception e) {}
}
public static void Main (string[] args) throws exception{
New MyThread (). Start ();
}
}

We'll be able to see the thread waiting, notice that the thread is waiting after it waits for no other thread to wake up, unless the JVM environment is forcibly exited.

So please remember:

[The Wait () method for a thread to invoke an object first obtains the object's monitoring lock, and once Wait () is called, the lock is released immediately]

Reprint Address: http://blog.zol.com.cn/860/article_859847.html

Java Multithreaded Example

Related Article

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.