Java threading and Walkthrough, thread pool Simple example

Source: Internet
Author: User

Java IO, collections, threads, strings, GC, JVM can be described as the most basic knowledge in Java, especially the complexity of threading, the corresponding difficult to understand, to the Java basic knowledge of solid, the above mentioned several aspects of the knowledge point must be proficient, so that they have mastered the basic knowledge of Java.

Summarize Java threading knowledge, usually touch threads, especially in Android development, threads are everywhere, a little attention will be error. In the Java thread is also ubiquitous, main is a threading, but is packaged, generally not touch.

My countless review experience tells me, the most rapid learning knowledge, the most profound method is to start from the problem, do not first look at the concept, encounter new knowledge points, the new concept of their own original knowledge of the first solution once, and then to see the relevant explanations, will find that the concept is so easy to understand. Don't say much nonsense, first the title:

1. With two threads, cross-output "123...56" and "abc...z", requiring the output as "12a34b67c ... 5556z ".

Analysis : This topic uses the knowledge point of the thread synchronization mutex. Thread 1 output-wake thread 2-> thread 1 Wait, thread 2 output-wake thread 1-> thread 2 wait ... Until the output is complete. The subject can almost comprehensively examine the knowledge of thread mutex. With these analyses, you can code:

/** * * @author MXR *classname threadtest * @Version 1.0 * @ModifiedBy 2014-10-27 * @Copyright rsdsyst */public class Threa Dtest extends Thread {class Thread1 implements Runnable {private Object _lock; public Thread1 (Object lock) {_lock = Lo ck @Override public void Run () {try {synchronized (_lock) {for (int i = 0; i <; i++) {System.out.print (     (2 * i + 1) + "" + (2 * i + 2));  _lock.notifyall ();//Wake Up Other Threads _lock.wait ();//release lock, Wait}}} catch (Interruptedexception e) {e.printstacktrace (); }}} class Thread2 implements Runnable {private Object _lock; public Thread2 (Object lock) {_lock = lock;} @Override PU    Blic void Run () {synchronized (_lock) {for (int i = 0; i <; i++) {System.out.print ((char) (' a ' + i)); _lock.notifyall ();//Wake Up other threads if (i<25) {try {_lock.wait ();//release lock, wait} catch (Interruptedexception e) {//TODO Auto-gen    Erated catch Blocke.printstacktrace ();} }}}}} public static void Main (string[] args) {ObjectLock=new Object ();  Thread T1=new Thread (new ThreadTest (). New Thread1 (lock));  Thread T2=new Thread (new ThreadTest (). New Thread2 (lock));  T1.start ();  T2.start ();   try {t1.join ();  T2.join ();  } catch (Interruptedexception e) {e.printstacktrace (); } }}
The code above is implemented according to the thought of analysis. The wait () above, Notifyall (), can only be used within a synchronous code block.

2. Use thread to realize the problem of bank withdraw, how to synchronize when error occurs.

/** * * @author MXR *classname threadtest * @Version 1.0 * @ModifiedBy 2014-10-27 * @Copyright rsdsyst */class user{int sum Count = 100; User () {}public <span style= "color: #ff0000;" >synchronized</span> void oper (int count) {sumcount = Sumcount-count; System.out.println ("has get:" +count+ ". The Sumcount is: "+sumcount);}}    public class ThreadTest extends Thread {User user;int usecount;    ThreadTest (user User,int usecount) {this.user = user;    This.usecount = Usecount; }public void Run () {try {sleep ()} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace () ;} User.oper (Usecount);} public static void Main (string[] args) {System.out.println (Thread.CurrentThread (). GetName () + ' is running '); User user = new user (); ThreadTest tt = new ThreadTest (user,30); ThreadTest tt1 = new ThreadTest (user,20); ThreadTest tt2 = new ThreadTest (user,30); ThreadTest tt3 = new ThreadTest (user,10); Tt.start (); Tt1.start (); Tt2.start (); Tt3.start (); System.out.printlN (Thread.CurrentThread (). GetName () + "is End"); }}
The code above, when no synchronized on the Oper, the result is wrong, because at the same time access to money, plus synchronization, a moment can only have one access, so avoid the error.

3. Simple understanding and application of the thread pool.

The thread pool is built with Executorservice and executors to provide threads for the program, and when there are many threads, it can save a lot of memory space, the thread pool is a queue of threads, and when the capacity of the queue is small, the extra threads will queue up to wait.

Bank withdrawals with a 2-capacity thread pool:

Import Java.util.concurrent.executorservice;import java.util.concurrent.executors;/** * * @author MXR *ClassName ThreadTest * @Version 1.0 * @ModifiedBy 2014-10-27 * @Copyright rsdsyst */class user{int sumcount = 100; User () {}public <span style= "color: #ff0000;" >synchronized</span> void oper (int count) {sumcount = Sumcount-count; System.out.println ("has get:" +count+ ". The Sumcount is: "+sumcount);}}    public class ThreadTest extends Thread {User user;int usecount;    ThreadTest (user User,int usecount) {this.user = user;    This.usecount = Usecount; }public void Run () {try {sleep ()} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace () ;} User.oper (Usecount);} public static void Main (string[] args) {System.out.println (Thread.CurrentThread (). GetName () + ' is running '); User user = new user (); ThreadTest tt = new ThreadTest (user,30); ThreadTest tt1 = new ThreadTest (user,20); ThreadTest tt2 = new ThreadTest (user,30); ThreadTest tt3 = new ThreadtEST (user,10); Executorservice pool = Executors.newfixedthreadpool (4); Pool.execute (TT); Pool.execute (TT1); Pool.execute (TT2); Pool.execute (TT3);    System.out.println (Thread.CurrentThread (). GetName () + "is End"); }}
Similarly, the thread pool itself is not synchronized, and the shared block needs to use synchronized to control synchronization.



Java threading and Walkthrough, thread pool Simple example

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.