Java multithreading (4) -- thread interaction and java Multithreading

Source: Internet
Author: User

Java multithreading (4) -- thread interaction and java Multithreading

Three basic functions used in thread Interaction:

Void y (); wake up a single thread waiting on this object monitor.

Void policyall (); wake up all threads waiting on this object monitor.

Void wait (); causes the current thread to wait until other threads call the notify () or yyall () method of this object.

Void wait (long timeout); the overloaded version of wait () also causes the current thread to wait until other threads call the notify () or yyall () method of this object, or wait until the specified time is exceeded.

Void wait (long timeout, int nanos); the overloaded version of wait () also causes the current thread to wait until other threads call the notify () or yyall () method of this object, or wait for more than a certain actual time to stop waiting, or another thread to interrupt the current thread.

Note the following in thread Interaction:

The wait (), Y (), and notifyAll () methods must be called from the synchronization environment. A thread cannot call Methods waiting for or notifying objects unless the thread has an object lock.

The thread obtains the Waiting List by executing the wait () method on the object. After that, the thread no longer executes any other commands until the notify () method of the object is called. When multiple threads wait on the same object, notify () will randomly wake up one of the threads to run them. If no thread waits, no processing is performed.

To execute the wait () method, the premise is that the current thread has the Lock of this object. After the wait () method is executed, this thread releases the Lock of this object, so that other threads can call y () or notifyAll () to wake up this thread. However, calling notify () does not mean that the thread will release the object lock. If the thread is still completing the synchronization code, the thread will not release the object lock when it completes the synchronization code block. Therefore, notify () does not mean that the lock is available.


Notes:

Wait (), Policy (), and policyall () do not belong to the Thread class, but to the Object class. That is to say, each Object has three methods. Because each object has its own lock, the lock is the basis of each object, and the operation lock method is also the basis of each object.

Wait () causes the wait of the current thread, instead of the thread class wait where the calling object is located, that is, the thread that owns the Lock of this object can call the wait () method.

Y () wakes up a single thread waiting on the current object monitor. If there are multiple threads waiting on this object, a thread is randomly woken up, the wake-up thread can continue to be executed until the current thread abandons the lock on this object. Notify () is the same as wait (), and must be called by the thread holding the Lock of this object. The same is true for yyall (), but policyall () it will wake up all threads waiting for this object and randomly select one from this thread.

All three methods must be used with synchronized, that is, the object lock must be obtained before the three methods can be called.



In a JAVA multi-threaded Program, under what circumstances will the yield () method of the thread be called?

From: developer online
Detailed analysis of Java multi-thread programming

I. multi-thread understanding

Multithreading is a mechanism that allows concurrent execution of Multiple Instruction Streams in a program. Each instruction stream is called a thread and is independent of each other.

A thread is also called a lightweight process. It has independent execution control like a process and is scheduled by the operating system. The difference is that the thread does not have independent storage space, instead, it shares a storage space with other threads in the process, which makes the communication between threads much simpler than the process.

The execution of multiple threads is concurrent, that is, logically "at the same time", regardless of whether it is physically "at the same time ". If the system only has one CPU, the real "at the same time" is impossible, but because the CPU speed is very fast, users do not feel the difference, so we do not need to care about it, you only need to imagine that each thread is executed at the same time.

The biggest difference between multithreading and traditional single-Thread Programming is that the control flow of each thread is independent of each other, so that the code between each thread is executed in disorder, the thread scheduling and synchronization issues will be discussed later.

2. Implement multithreading in Java

What do we need to do to create a new thread? Obviously, we must specify the code to be executed by this thread, and this is all we need to do to implement multithreading in Java!

Amazing! How does Java achieve this? Passed class! As a fully object-oriented language, Java provides a class of java. lang. thread to facilitate multi-threaded programming. This class provides a large number of methods to facilitate our control of various threads. We will discuss this class in the future.

So how can we provide the code to be executed by threads for Java? Let's take a look at the Thread class. The most important method of the Thread class is run (), which is called by the Thread class method start () and provides the code to be executed by our Thread. To specify our own code, we only need to overwrite it!

Method 1: Inherit the Thread class and overwrite the run () method. In the subclass of the created Thread class, rewrite run () and add the code to be executed by the Thread. The following is an example:

Public class MyThread extends Thread
{
Int count = 1, number;
Public MyThread (int num)
{
Number = num;
System. out. println
("Create thread" + number );
}
Public void run (){
While (true ){
System. out. println
("Thread" + number + ": count" + count );
If (++ count = 6) return;
}
}
Public static void main (String args [])
{
For (int I = 0;
I <5; I ++) new MyThread (I + 1). start ();
}
}

This method is simple and clear, and conforms to everyone's habits. However, it also has a major drawback, that is, if our class has been inherited from a class (for example, the Applet must inherit from the Applet Class), we cannot inherit from the Thread class. If we do not want to create a new class, what should I do?

We may wish to explore a new method: instead of creating a subclass of the Thread class, we can directly use it, so we can only pass our method as a parameter to the Thread class instance, similar to callback functions. But Java has no pointer. We can only pass an instance of the class containing this method.

So how can we limit that this class must contain this method? Of course, the interface is used! (Although the abstract class can also be satisfied, it must be inherited, and the rest of our full text...>

Write a multi-threaded program in JAVA, write four threads, two of which add 1 to a variable, the other two minus 1 to a variable, and output

What do we need to do to create a new thread? Obviously, we must specify the code to be executed by this thread, and this is all we need to do to implement multithreading in Java!

Amazing! How does Java achieve this? Passed class! As a fully object-oriented language, Java provides a class of java. lang. thread to facilitate multi-threaded programming. This class provides a large number of methods to facilitate our control of various threads. We will discuss this class in the future.

So how can we provide the code to be executed by threads for Java? Let's take a look at the Thread class. The most important method of the Thread class is run (), which is called by the Thread class method start () and provides the code to be executed by our Thread. To specify our own code, we only need to overwrite it!

Method 1: Inherit the Thread class and overwrite the run () method. In the subclass of the created Thread class, rewrite run () and add the code to be executed by the Thread. The following is an example:

Public class MyThread extends Thread {

Int count = 1, number;

Public MyThread (int num ){

Number = num;

System. out. println ("creation thread" + number );

}

Public void run (){

While (true ){

System. out. println ("Thread" + number + ": count" + count );

If (++ count = 6) return;

}

}

Public static void main (String args []) {

For (int I = 0; I <5; I ++) new MyThread (I + 1). start ();

}

}

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.