Java thread Series (iv) threading communication

Source: Internet
Author: User
Tags volatile

Java thread Series (iv) threading communication One, traditional communication
 Public Static void Main(string[] args) {//volatile achieves two threads of data visibility    Private volatile StaticList List =NewArrayList (); Thread T1 =NewThread (NewRunnable () {//(1)         Public void Run() {Try{ for(inti =0; I <Ten; i++) {list.Add(i); System. out.println(Thread.CurrentThread().GetName() +"Thread add section"+ (i +1) +"Elements:"); Thread.Sleep( -); }            }Catch(Interruptedexception e) {e.Printstacktrace(); }        }    },"T1"); Thread t2 =NewThread (NewRunnable () {//(2)         Public void Run() { while(true){if(list.size() ==5){//do something                    Throw NewRuntimeException (Thread.CurrentThread().GetName() +"Thread is notified by size ="+ list.size() +"Thread stopped ..."); }            }        }    },"T2"); T1.Start(); T2.Start();}
    1. T1 threads continually put the produced data into the list collection

    2. T2 thread on while loop listening T1 thread, although can implement List.size () ==5 real-time notification T2 thread , but too wasteful performance, consider await/notify improving performance, program execution results are as follows:

t1线程添加第1个元素..t1线程添加第2个元素..t1线程添加第3个元素..t1线程添加第4个元素..t1线程添加第5个元素..Exception in thread "t2" java.lang.RuntimeException: t2线程接到通知 size = 5 线程停止..    at com.github.binarylei.thread._2_1conn.ListAdvice1$2.run(ListAdvice1.java:35)    at java.lang.Thread.run(Thread.java:745)t1线程添加第6个元素..t1线程添加第7个元素..t1线程添加第8个元素..t1线程添加第9个元素..t1线程添加第10个元素..
Ii. wait/notify Realization of communication
/*** Use the Wait/notify method to implement thread-singled communication (note that both methods are methods of the object class)* 1. Wait and notity must be used with the Synchronized keyword* 2. Wait method (Close thread) release lock, notify (wakeup thread) method does not release lock* Cons: Notifications are not real-time, using Countdownlatch for real-time notifications */ Public Static void Main(string[] args) {Private volatile StaticList List =NewArrayList ();FinalObject lock =NewObject (); Thread T1 =NewThread (NewRunnable () {//(1)         Public void Run() {Try{synchronized(lock) {System. out.println("T1 start ..."); for(inti =0; I <Ten; i++) {list.Add(i); System. out.println(Thread.CurrentThread().GetName() +"Thread add section"+ (i +1) +"Elements:"); Thread.Sleep( -);if(list.size() ==5) {System. out.println("Notification has been issued."); Lock.Notify(); }                    }                }            }Catch(Interruptedexception e) {e.Printstacktrace(); }        }    },"T1"); Thread t2 =NewThread (NewRunnable () {//(2)         Public void Run() {synchronized(lock) {System. out.println("T2 start ...");if(list.size() !=5){Try{lock.wait(); }Catch(Interruptedexception e) {e.Printstacktrace(); }                }//do something                Throw NewRuntimeException (Thread.CurrentThread().GetName() +"Thread is notified by size ="+ list.size() +"Thread stopped ..."); }        }    },"T2");}
    1. T1 threads when list.size()==5 lock.notify() waking T2 threads, Note that they wait/notify must be synchronized used in conjunction .

    2. The T2 thread is lock.wait() blocked until the thread is called lock.notify() by the T1 thread, and if no thread wakes up the T2 thread, the T2 thread is stuck in a blocking state. In this case, if the T1 line enters upgradeable is started, then the T2 thread call will lock.wait() never be executed. The results of the program execution are as follows:.

t2启动..t1启动..t1线程添加第1个元素..t1线程添加第2个元素..t1线程添加第3个元素..t1线程添加第4个元素..t1线程添加第5个元素..已经发出通知..t1线程添加第6个元素..t1线程添加第7个元素..t1线程添加第8个元素..t1线程添加第9个元素..t1线程添加第10个元素..Exception in thread "t2" java.lang.RuntimeException: t2线程接到通知 size = 10 线程停止..    at com.github.binarylei.thread._2_1conn.ListAdd2$2.run(ListAdd2.java:51)    at java.lang.Thread.run(Thread.java:745)
    1. Because the T1 thread lock.notify() does not release the lock, the T2 thread is awakened but cannot acquire the lock, so the notification is less real-time, and only the T1 thread performs the release lock after the T2 thread can get the lock to perform the corresponding operation, the solution: usingCountDownLatch
Countdownlatch realization of real-time communication
 Public Static void Main(string[] args) {Private volatile StaticList List =NewArrayList ();FinalCountdownlatch Countdownlatch =NewCountdownlatch (1);//(1)Thread T1 =NewThread (NewRunnable () { Public void Run() {Try{System. out.println("T1 start ..."); for(inti =0; I <Ten; i++) {list.Add(i); System. out.println(Thread.CurrentThread().GetName() +"Thread add section"+ (i +1) +"Elements:"); Thread.Sleep( -);if(list.size() ==5) {System. out.println("Notification has been issued."); Countdownlatch.Countdown();//(2)}                }            }Catch(Interruptedexception e) {e.Printstacktrace(); }        }    },"T1"); Thread t2 =NewThread (NewRunnable () { Public void Run() {System. out.println("T2 start ...");if(list.size() !=5){Try{Countdownlatch.await();//(3)}Catch(Interruptedexception e) {e.Printstacktrace(); }            }//do something            Throw NewRuntimeException (Thread.CurrentThread().GetName() +"Thread is notified by size ="+ list.size() +"Thread stopped ..."); }    },"T2"); T1.Start(); T2.Start();}
    1. The Countdownlatch synchronization tool class, which allows one or more threads to wait until the operation of another thread has finished executing, and parameter 1 indicates the number of threads that need to wait, specifically the arguments must be called several timescountDownLatch.countDown()

    2. countDownLatch.countDown()Wake-Up thread

    3. countDownLatch.await()Blocking threads, the program execution results are as follows:

t1启动..t1线程添加第1个元素..t2启动..t1线程添加第2个元素..t1线程添加第3个元素..t1线程添加第4个元素..t1线程添加第5个元素..已经发出通知..Exception in thread "t2" java.lang.RuntimeException: t2线程接到通知 size = 5 线程停止..t1线程添加第6个元素..    at com.github.binarylei.thread._2_1conn.ListAdd3$2.run(ListAdd3.java:47)    at java.lang.Thread.run(Thread.java:745)t1线程添加第7个元素..t1线程添加第8个元素..t1线程添加第9个元素..t1线程添加第10个元素..
Iv. ThreadLocal

ThreadLocal is a thread-local variable, which is a non-locking solution for concurrent access variables between multiple threads.

ThreadLocal and synchronized compare?

    1. Unlike synchronized, such as locking, ThreadLocal does not provide locks at all, and uses space-time-changing means to provide each thread with a separate copy of the variable to ensure thread safety.

    2. Performance, ThreadLocal does not have an absolute advantage, when concurrency is not very high, lock performance will be better, but as a set of unlocked solutions, in high concurrency or competitive scenes, the use of ThreadLocal can reduce the lock competition to a certain extent.

public static void main(String[] args) throws InterruptedException {    final ThreadLocal<String> th = new ThreadLocal<String>();    Thread t1 = new Thread(new Runnable() {        public void run() {            th.set("张三");            System.out.println(th.get()); // => "张三"        }    }, "t1");        Thread t2 = new Thread(new Runnable() {        public void run() {            try {                Thread.sleep(1000);                th.set("李四");                System.out.println(th.get()); // => "李四"            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }, "t2");        t1.start(); //t1:张三    t2.start(); //t2:李四}
Five, custom synchronization class window-queue

Java provides a number of synchronization class containers, which are thread-safe , such as vectors, HashTable, and so on. These synchronization class containers are implemented by factory methods such as Collections.synchronizedmap , with the underlying use of the Synchronized keyword, where only one thread accesses the container at a time. The following implements a synchronization class window of its own.

 import Java.util.linkedlist;public class Myqueue {private LinkedList list = new LinkedList (); private int max = 5; private int min = 1; Private Object lock = new Object (); public void put (Object obj) {//(1) synchronized (lock) {while (list.size () = = max) { try {lock.wait (); } catch (Interruptedexception e) {; }} list.add (obj); Lock.notify (); System.out.println ("put element:" + obj); }} public object Take () {//(2) object obj; Synchronized (lock) {while (list.size () = = min) {try {lock.wait (); } catch (Interruptedexception e) {; }} obj = List.removefirst (); Lock.notify (); SYSTEM.OUT.PRINTLN ("take element:" + obj); } return obj; }}

Test

public static void main(String[] args) {    final MyQueue myQueue = new MyQueue();    myQueue.put("a");    myQueue.put("b");    myQueue.put("c");    myQueue.put("d");    myQueue.put("e");    new Thread(new Runnable() {        @Override        public void run() {            myQueue.put("f");            myQueue.put("g");            myQueue.put("h");            myQueue.put("i");        }    }).start();    new Thread(new Runnable() {        @Override        public void run() {            myQueue.take();            myQueue.take();            myQueue.take();        }    }).start();}

Record a little bit every day. Content may not be important, but habits are important!

Java thread Series (iv) threading communication

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.