Java multi-thread 3 thread collaboration and communication instance, java multi-thread

Source: Internet
Author: User

Java multi-thread 3 thread collaboration and communication instance, java multi-thread

The difficulty of Multithreading is mainly the multi-thread communication and collaboration. The common Synchronization Methods mentioned in the second part of the preceding notes are as follows:

1. multi-threaded Implementation of bank deposits and withdrawals, Lock and conditional Condition. Additional: Use monitors for inter-thread Communication

2. producer consumer implementation, using the writable list self-writing buffer.

3. multi-thread blocking queue learning: Use blocking queues to quickly implement producer and consumer models. Additional: Use a Boolean variable to close the thread

Among the three thread synchronization methods, the instance here uses the Lock to synchronize variables because it is flexible and intuitive.

To synchronize variables, we need to make "calls" between multiple threads, that is, after a thread completes a certain condition, it tells other threads that I have completed this condition, you can proceed. The following is the synchronization method defined by the conditional interface Condition provided by java:

Import java. util. concurrent. executorService; import java. util. concurrent. executors; import java. util. concurrent. locks. condition; import java. util. concurrent. locks. lock; import java. util. concurrent. locks. reentrantLock; public class ThreadCooperation {private static Account account Account = new Account (); public static void main (String [] args) {// create a thread pool ExecutorService executor = export cute (new deposittask(registry.execuutor.exe cute (new WithdrawTask ();} // save public static class DepositTask implements Runnable {@ Overridepublic void run () {try {while (true) {account. deposit (int) (Math. random () * 1000) + 1); Thread. sleep (1000) ;}} catch (InterruptedException e) {e. printStackTrace () ;}} public static class WithdrawTask implements Runnable {@ Overridepublic void run () {try {while (true) {account. withdraw (int) (Math. random () * 1000) + 1); Thread. sleep (500) ;}} catch (InterruptedException e) {e. printStackTrace ();}}} public static class Account {// a Lock is an instance of the Lock interface. It defines the locking and release methods. ReentrantLock is the specific implementation of private static Lock for creating mutually exclusive locks. lock = new ReentrantLock (); // create a condition with the notification sending lock provided that the lock interface private static Condition newDeposit = lock is implemented. newCondition (); private int balance = 0; public int getBalance () {return balance;} public void withdraw (int amount) {lock. lock (); try {while (balance <amount) {System. out. println ("\ t insufficient money, waiting for saving"); newDeposit. await ();} balance-= amount; System. out. println ("\ t fetch" + amount + "block money \ t remaining" + getBalance ();} catch (InterruptedException e) {e. printStackTrace ();} finally {lock. unlock () ;}} public void deposit (int amount) {lock. lock (); try {balance + = amount; System. out. println ("saved" + amount + "block money"); newDeposit. signalAll (); // send messages to wake up all threads} finally {lock. unlock ();}}}}

Run import java. util. concurrent. executorService; import java. util. concurrent. executors; import java. util. concurrent. locks. condition; import java. util. concurrent. locks. lock; import java. util. concurrent. locks. reentrantLock; // producer consumer public class ConsumerProducer {private static Buffer buffer Buffer = new Buffer (); public static void main (String [] args) {ExecutorService executor = executors.newfixedthreadpool(2%%%executor.exe cute (new producertask(%%%%%executor.exe cute (new ConsumerTask (); executor. shutdown ();} public static class ProducerTask implements Runnable {@ Overridepublic void run () {int I = 1; try {while (true) {System. out. println ("producer write data" + I); buffer. write (I ++); Thread. sleep (int) (Math. random () * 80);} catch (InterruptedException e) {e. printStackTrace () ;}} public static class ConsumerTask implements Runnable {public void run () {try {while (true) {System. out. println ("\ t consumption read data" + buffer. read (); Thread. sleep (int) (Math. random () * 100);} catch (InterruptedException e) {e. printStackTrace () ;}} public static class Buffer {private static final int CAPACTIY = 4; // Buffer Capacity private java. util. queue list <Integer> queue = new java. util. optional list <Integer> (); private static Lock lock = new ReentrantLock (); private static Condition notEmpty = lock. newCondition (); private static Condition notFull = lock. newCondition (); public void write (int value) {lock. lock (); try {while (queue. size () = CAPACTIY) {System. out. println ("buffer full"); notFull. await ();} queue. offer (value); notEmpty. signalAll (); // notify all the cases where the buffer is not empty} catch (InterruptedException ex) {ex. printStackTrace ();} finally {lock. unlock () ;}@ SuppressWarnings ("finally") public int read () {int value = 0; lock. lock (); try {while (queue. isEmpty () {System. out. println ("\ t buffer is empty, waiting for non-empty buffer"); notEmpty. await ();} value = queue. remove (); notFull. signal ();} catch (InterruptedException ex) {ex. printStackTrace ();} finally {lock. unlock (); return value ;}}}}

 

Run import java. util. concurrent. arrayBlockingQueue; import java. util. concurrent. executorService; import java. util. concurrent. executors; public class ConsumerProducerUsingBlockQueue {private static ArrayBlockingQueue <Integer> buffer = new ArrayBlockingQueue <Integer> (2); public static void main (String [] args) {ExecutorService executor = executors.newfixedthreadpool(2%%%executor.exe cute (new consumer(%%%%%executor.exe cute (new Producer (); try {Thread. sleep (100); executor. shutdownNow (); // brute force shutdown. An error is returned. It is not recommended that} catch (InterruptedException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} public static class Consumer implements Runnable {@ Overridepublic void run () {try {int I = 1; while (true) {System. out. println ("producer write:" + I); buffer. put (I ++); Thread. sleep (int) (Math. random () * 1000);} catch (InterruptedException ex) {ex. printStackTrace () ;}} public static class Producer implements Runnable {@ Overridepublic void run () {try {while (true) {System. out. println ("\ t consumer fetch" + buffer. take (); Thread. sleep (int) (Math. random () * 10000);} catch (InterruptedException ex) {ex. printStackTrace ();}}}}

 

Run: import java. util. concurrent. executorService; import java. util. concurrent. executors; import java. util. concurrent. linkedBlockingQueue; public class A_Control_stop {private static LinkedBlockingQueue <String> buffer = new LinkedBlockingQueue <String> (); public static void main (String [] args) {ExecutorService executor = executors.newfixedthreadpool(2%%%executor.exe cute (new consumer(%%%%%executor.exe cute (new P Roducer (); executor. shutdown (); while (! Executor. isTerminated () {} System. out. println ("All threads end normally");} public static class Consumer implements Runnable {private volatile boolean exit = false; @ Overridepublic void run () {try {int I = 0; String [] str = {"as", "d", "sd", "ew", "sdfg", "esfr "}; while (! Exit) {System. out. println ("producer write:" + str [I]); buffer. put (str [I ++]); Thread. sleep (int) (Math. random () * 10); if (5 = I) {exit = true ;}} catch (InterruptedException ex) {ex. printStackTrace () ;}} public static class Producer implements Runnable {private volatile boolean exit = false; @ Overridepublic void run () {try {int I = 0; while (! Exit) {System. out. println ("\ t consumer fetch" + buffer. take (); I ++; Thread. sleep (int) (Math. random () * 10); if (5 = I) {exit = true ;}} catch (InterruptedException ex) {ex. printStackTrace ();}}}}

 

I think this article is good about blocking queues. I suggest you talk about concurrency ---- blocking queues in Java.

After a few days, I learned a little about multithreading. Note: These articles mainly refer to java programming language design advanced Article 8th. the books written by foreigners are really good, but now java has been updated to java 8. I have seen my articles on some other websites, but I have not explained the reposted information. It is estimated that my articles have been directly collected.

This article is from the blog garden. For more information, see the source.


Java multithreading issues A, B, C three different threads A are responsible for sending data, B is responsible for network connection, C is responsible for data processing

The order of BAC is that, before starting the next thread, you need to wait for the result returned by another thread. You can work with the interface to call back and forth,
For example:
Class Main implement BListener {
Public void startTask (){
Start line B, input the listener instance, and call it back and forth;
}
// Override
Public void BTaskComplete (){
The line B is successfully executed;

Start thread;
}

}

Class B extends Thread {
Listener instances can be obtained during construction;
Public void run (){
...
After the execution is completed, the result is Listener. BTaskComplete ();

}

}
It's just a rough idea, but it's quite clear. I hope it will help you.

Java multithreading provides comprehensive methods and functions that can be annotated. It is best to have examples,

Java Memory Model
Different platforms have different memory models, but the jvm memory model specifications are uniform. Java's multi-thread concurrency problems will eventually be reflected in the java memory model. The so-called thread security is nothing more than controlling the orderly access or modification of a resource by multiple threads. The java memory model has two major problems to solve: visibility and orderliness. We all know that a computer has a high-speed cache, and not every time the processor processes data, the memory is used. JVM defines its own memory model and shields the memory management details of the underlying platform. For java developers, the solution is to solve the problem of multi-thread visibility and orderliness Based on the jvm memory model.
So what is visibility? Multiple Threads cannot communicate with each other. Communication between them can only be performed through shared variables. The Java Memory Model (JMM) specifies that the jvm has the primary memory, which is shared by multiple threads. When a new object is created, it is also allocated to the primary memory. Each thread has its own working memory, which stores copies of some objects in the primary memory, of course, the thread's working memory size is limited. When a thread operates an object, the execution sequence is as follows:
(1) copy the variable from the primary memory to the current working memory (read and load)
(2) execute the code and change the value of shared variables (use and assign)
(3) use the working memory data to refresh the content related to the primary storage (store and write) JVM specification to define the thread's operation commands for the primary storage: read, load, use, assign, store, write. When a shared variable has copies in the working memory of multiple threads, if a thread modifies the shared variable, other threads should be able to see the modified value, this is the visibility of multithreading.
So what is orderliness? When a thread references a variable, it cannot be referenced directly from the main memory. If the variable does not exist in the thread's working memory, a copy is copied from the main memory to the working memory, this process is read-load, and the thread will reference this copy after completion. When the same thread references this field again, it is possible to obtain a copy of the variable from the primary storage (read-load-use) Again, or directly reference the original copy (use ), that is to say, the order of read, load, and use can be determined by the JVM implementation system.
The thread cannot directly assign values to fields in the primary memory. It will assign the values to the variable copy (assign) in the working memory ), after the completion, the copy of the variable will be synchronized to the primary storage area (store-write). As to when the synchronization will pass, it is determined by the JVM implementation system. with this field, the field is assigned to the working memory from the main memory. This process is read-load, and the thread will reference this copy of the variable after completion, when the same thread repeatedly assigns values to fields, for example:
For (int I = 0; I <10; I ++)
A ++;
The thread may only assign values to copies in the working memory and synchronize them to the primary storage zone only after the last assignment. Therefore, the order of assign, store, and weite can be determined by the JVM implementation system. Suppose there is a shared variable x, thread a executes x = x + 1. From the above description, we can know that x = x + 1 is not an atomic operation, and its execution process is as follows:
1. Read the copy of variable x from the primary memory to the working memory.
2 Add 1 to x
3. Write the value after adding x and 1 back to the primary storage.
If another thread B executes x = X-1, the execution process is as follows:
1. Read the copy of variable x from the primary memory to the working memory.
2 minus 1 for x
3. Write the value after x minus 1 to the primary storage.
Obviously, the final x value is unreliable. Assume that x is now 10, thread a is added to 1, and thread B is reduced to 1. On the surface, it seems that the final x is still 10, but this may happen in the case of multithreading:
1: thread a reads x copies from the primary memory to the working memory. The x value in the working memory is 10.
2: thread B reads x copies from the primary memory to the working memory. The x value in the working memory is 10.
3: thread a adds x in the working memory to 1, and the x value in the working memory is 11.
4: thread a will... the remaining full text>

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.