Java Concurrency Deep Learning (i)

Source: Internet
Author: User

Introduction to concurrent programming

Concurrent programming can help us divide our programs into separate, separate, running tasks. With multithreading, each of these separate tasks is driven by the execution thread. A thread is a single sequential control flow in a process, so a single process can have multiple concurrently executed tasks, but the program makes each task seem to have its own CPU, and its underlying mechanism is to slice the CPU time. The CPU takes turns to allocate time for each task.

thread sharing static variables

Each thread has its own separate address space, where the static member variables can be shared by multiple threads, such as the address of the I,i in the program below is unique, and is always stored in the static zone, so every time I load read writes is likely to occur unfair competition, in order to ensure read and write security, Especially for I to lock synchronized, so as to ensure the safe read and write.


Package concurrency;/** * Concurrency problem, multi-threaded static variables can be shared I * @author ZZW922CN * */public class Countrunnable implements Runnable {privat e static Integer i=0; @Overridepublic void Run () {synchronized (i) {System.out.println (Thread.CurrentThread (). GetName () + ":" + (++i));}}}



Test code:



Package Concurrency;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;public class Test1 {public static void main (string[] args) {//executors.newcachedthreadpool () is used to create a new thread pool, and if there are idle threads to use it, Otherwise, create a new thread executorservice Newcachedthreadpool = Executors.newcachedthreadpool (); thread[] thread = new thread[10];for (int i=0;i<thread.length;i++) {thread[i]=new thread (new countrunnable ()); Newcachedthreadpool.submit (Thread[i]);} Newcachedthreadpool.shutdown ();}}



Test results:



Pool-1-thread-2:2pool-1-thread-4:4pool-1-thread-3:3pool-1-thread-1:1pool-1-thread-5:5pool-1-thread-6 : 6pool-1-thread-7:7pool-1-thread-8:8pool-1-thread-10:9pool-1-thread-9:10



return value from task (callable interface)

Sometimes, when we split a task, we also want each task to be executed to return some data to the main process, which we can implement using the implementation of the callable interface. Callable is a generic interface, where the method that must be implemented is the call () method, which is the return value that the task submits to the main thread, because it is generic, so we can return an object of any type.

Let's take a split of multiple summation tasks, with the following code:


Package Concurrency;import Java.util.concurrent.callable;public class Countnumbertask implements Callable<integer > {private int num;/** * constructor * @param num End number */public countnumbertask (int num) {this.num = num;} /** * Implements the call function, returns the result */@Overridepublic Integer call () throws Exception {int sum=0;for (int i=1;i<=num;i++) {sum+=i;} return sum;}}



Test code:



Package Concurrency;import Java.util.concurrent.executionexception;import Java.util.concurrent.ExecutorService; Import Java.util.concurrent.executors;import java.util.concurrent.future;/** * takes 26 seconds * @author ZZW922CN * */public class countnumbertest {public static void main (string[] args) {Long T1 = System.currenttimemillis (); Executorservice Newcachedthreadpool = Executors.newfixedthreadpool (2); for (int i=1;i<=300000;i++) {Future< integer> Submit = Newcachedthreadpool.submit (new Countnumbertask (i)); try {integer integer = Submit.get (); System.out.println (integer);} catch (Interruptedexception | Executionexception e) {e.printstacktrace ();}} Newcachedthreadpool.shutdown (); Long t2 = System.currenttimemillis (); System.out.println ("Multithreading Time Consuming" + (T2-T1)/1000.0+ "S");}}



To compare with the traditional single-threaded approach, a single-threaded program is also written:



Package concurrency;/** * takes 37 seconds * @author ZZW922CN * */public class CountNumberTest2 {public static void main (string[] Arg s) {Long T1 = System.currenttimemillis (); for (int i=1;i<=300000;i++) {int sum=0;for (int j=0;j<=i;j++) {sum+=j;} SYSTEM.OUT.PRINTLN (sum);} Long t2 = System.currenttimemillis (); SYSTEM.OUT.PRINTLN ("Single thread Time Consuming" + (T2-T1)/1000.0+ "S");}}



After running, it is found that using multithreading takes 26s and a single thread spends 37s.


Daemon Threads

The so-called Daemon thread (also known as a background thread) is a thread that provides a common service in the background while the program is running, and this thread is not an integral part of the program. When all non-daemons end, the program terminates, and it kills all the daemon threads of the program, and the daemon thread does not execute a finally statement block when it is killed.


Package Concurrency;public class Deamonrunnable implements Runnable {@Overridepublic void run () {try {while (true) {Thread . Sleep (100); System.out.println (Thread.CurrentThread () + "" +this);}} catch (Interruptedexception ex) {System.out.println ("Sleep () interrupted!");}}}



Test class:



Package Concurrency;import Java.util.concurrent.timeunit;public class Deamonrunnabletest {public static void main ( String[] args) throws interruptedexception {for (int i=0;i<10;i++) {thread thread = new Thread (new Deamonrunnable ()); th Read.setdaemon (True); Thread.Start ();} Set the main thread to hibernate so you can see the daemon thread TimeUnit.MILLISECONDS.sleep (175);}}



Test results:



Thread[thread-1,5,main] [email protected]thread[thread-6,5,main] [email protected]thread[thread-5,5,main] [email Protected]thread[thread-0,5,main] [email protected]thread[thread-2,5,main] concurrency. Deam[email Protected]thread[thread-4,5,main] [email protected]thread[thread-3,5,main] [email protected]thread[ Thread-9,5,main] [email protected]thread[thread-8,5,main] [email protected]thread[thread-7,5,main] [email protected]



Child threads of the daemon thread

Running the results from the following code we will find that for the daemon thread, all its child threads are also daemon threads.


Package Concurrency;public class Daemon implements Runnable {private thread[] t=new thread[10]; @Overridepublic void Run () {//TODO auto-generated method stubfor (int i=0;i<t.length;i++) {t[i]=new Thread (new Daemonspawn ()); T[i].start (); System.out.println (t[i]+ "has started!");} for (int. i=0;i<t.length;i++) {System.out.println (t[i]+ "is Daemonthread:" +t[i].isdaemon ());} while (true) {Thread.yield ();}}}



Package Concurrency;public class Daemonspawn implements Runnable {@Overridepublic void run () {while (true) {// Concession Thread.yield ();}}}



Test code:



Package Concurrency;public class Daemontest {public static void main (string[] args) throws interruptedexception {Thread th Read = new Thread (new Daemon ()); Thread.setdaemon (true); Thread.Start (); System.out.println (thread+ "Isdaemonthread:" +thread.isdaemon ()); Thread.Sleep (100);}}



Test results:



Thread[thread-0,5,main]isdaemonthread:truethread[thread-1,5,main]has started! Thread[thread-2,5,main]has started! Thread[thread-3,5,main]has started! Thread[thread-4,5,main]has started! Thread[thread-5,5,main]has started! Thread[thread-6,5,main]has started! Thread[thread-7,5,main]has started! Thread[thread-8,5,main]has started! Thread[thread-9,5,main]has started! Thread[thread-10,5,main]has started! Thread[thread-1,5,main]is Daemonthread:truethread[thread-2,5,main]is Daemonthread:truethread[thread-3,5,main]is Daemonthread:truethread[thread-4,5,main]is Daemonthread:truethread[thread-5,5,main]is DaemonThread:trueThread[ Thread-6,5,main]is Daemonthread:truethread[thread-7,5,main]is Daemonthread:truethread[thread-8,5,main]is Daemonthread:truethread[thread-9,5,main]is Daemonthread:truethread[thread-10,5,main]is DaemonThread:true






Java Concurrency Deep Learning (i)

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.