Java multithreading--two real-world application scenario simulations

Source: Internet
Author: User

Java multithreading-Two real-world scenarios simulating the cat from Schrödinger

A

First of all, simulate the sending and receiving of information. The scenario is this:

Just like I did before the message sent, one is the server, one is the client. Send, to ensure that information 100% sent to the client, then to the client, the client returned a message to tell the server, has been received. When the server has not received the message returned by the client, the server will continue to send this information until the client sends back a confirmation message, and then delete the duplicate sent message.

To simulate this scenario, here are two threads to write, one to send, one to receive, the information to send, to save to thread-safe objects, to prevent thread-safety problems, and to use Concurrenthashmap.

Send code:

Package com. testthread;/* * *  @author Schrödinger hungry cat *  * */import Java.util.map.entry;import Java.util.concurrent.concurrenthashmap;public class Pushthread extends Thread {    @Override public    void Run () { c4/>//TODO auto-generated Method stub        try {            sleep (6000);            while (MainThread.pushmessage.size () >0) {                //re-send Message                for (Entry<integer, string> hashMap: MainThread.pushmessage.entrySet ()) {                    System.out.println ("Message ID:" +hashmap.getkey () + "not sent successfully, Resend here:" + Hashmap.getvalue ());                }                Sleep (+);            }        } catch (Interruptedexception e) {            //TODO auto-generated catch block            e.printstacktrace ();        }    }    }

Send code, is constantly traversing the memory object Councurrenthashmap, from which to take out information, constantly resend. Where Mainthread.pushmessage is a memory object and is defined in the last piece of code.

When the message is acknowledged, another thread deletes the memory object.

Code to delete:

Package com. testthread;/* * *  @author Schrödinger hungry cat *  * */import java.util.map.entry;public class Removethread extends Thread {    @ Override public    Void Run () {        //TODO auto-generated method stub        try {for            (int i = 0; i < 10000; i++) {                sleep (+);                For (Entry<integer, string> map:MainThread.pushmessage.entrySet ()) {                    if (Map.getkey () ==i) {                        System.out.println ("Successfully received ID:" +map.getkey () + "Return information, delete this element");                        MainThread.pushmessage.remove (Map.getkey ());                    }                }                System.out.println ("The number of elements in the memory object is:" +mainthread.pushmessage.size ());}        } catch (Interruptedexception e) {            //TODO auto-generated catch block            e.printstacktrace ();        }    }    }

Here is to delete the received information and then remove it from memory and send it again.

Then write a main class entry:

Package com. testthread;/* * *  @author Schrödinger hungry cat *  * */import Java.util.concurrent.concurrenthashmap;public class Mainthread { C3/>public static Concurrenthashmap<integer, string> pushmessage=new concurrenthashmap<integer,string> ( );    public static void Main (string[] args) {        for (int i = 0; i < i++) {            pushmessage.put (i, "the message is a message with an ID of" +i+ "); c7/>}        Thread pushthread=new pushthread ();        Thread remove=new removethread ();        Pushthread.start ();        Remove.start ();        for (int i = ten; i <; i++) {            pushmessage.put (i, "another wave arrives, the message is the message with the ID" +i+ ");}}}    

So two threads can take turns doing their own things without causing data security problems. In this way, combined with ANDROIDPN's push mechanism, it will be more in line with the actual production of the application.

(b) Multi-threaded synchronization counter

Multi-threaded synchronization counter, according to the truth can also be processed according to the above way, define a variable like concurrenthashmap. In Java, there are also other variables, atomic variables Atomic, Atomiclong,Atomicinteger,atomicreference.

If in the multi-threaded environment to give some values to assign a unique ID, this time, it is necessary to consider the ID of the security issue, that is, the consistency of the problem, can not be repeated. Here are two implementations of the code:

Package Com.test;public class ThreadCount {public    static void Main (string[] args) {                thread[] threads=new thread[ 10000];        for (int i = 0; i < 10000; i++) {            threads[i]=new athread ();            Threads[i].start ();}}}    Class Athread extends thread{    @Override public    void Run () {        //TODO auto-generated method stub        @ Suppresswarnings ("unused")        Counter counter=new Counter ();        System.out.println (Counter.calnum ());    }    } Class counter{     private static long num;     Public Counter () {         synchronized (counter.class) {            num++;        }     }     public static synchronized Long Calnum () {         return num;     }}

Here, 10,000 threads are created, each of which accesses the counter and increments the values in the construction method.

In the counter, there are two times used in synchronization, many people say that with synchronization, often impact on performance. So, with the second atom variable, this performance should be better.

Code:

Package Com.test;import Java.util.concurrent.atomic.atomiclong;public class ThreadCount {public    static void main ( String[] args) {                thread[] threads=new thread[10000];        for (int i = 0; i < 10000; i++) {            threads[i]=new athread ();            Threads[i].start ();}}}    Class Athread extends thread{    @Override public    void Run () {        System.out.println (Mycounter.calnum ());    }    }class counter{     private static long num;     Public Counter () {         synchronized (counter.class) {            num++;        }     }     public static synchronized Long Calnum () {         return num;     }} Class mycounter{    private static Atomiclong num=new Atomiclong ();        public static synchronized Long Calnum () {        return num.incrementandget ();}    }


In this case, when the counter is called, the new MyCounter object is not needed directly.

This allows you to call MyCounter's Calnum method directly as a tool class.

Java multithreading-two real-world scenario simulations

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.