Several realization ways of multithreading _ multithreading

Source: Internet
Author: User
One: The meaning of multithreading

Usually the development of the thread is a thing, such as Tomcat in the servlet is the threads, no thread how we provide multi-user access. But many developers who have just begun to touch threads have suffered a lot. How to do a simple thread development model framework for everyone from single-threaded development quickly into multithreaded development, this is not a simple thing.

What is the specific thread? First look at what the process is, the process is a program executed in the system, this program can use memory, processor, file system and other related resources. For example, QQ software, Eclipse, Tomcat, etc. is an EXE program, run started up is a process. Why multiple threads are required. If each process is handled alone one thing can not be handled by multiple tasks simultaneously, such as we open QQ can only chat with a person, we use Eclipse Development code can not compile code, we request Tomcat service can only serve a user request, then I think we are still in primitive society. The purpose of multithreading is to allow a process to handle multiple things or requests at the same time. For example, now we use QQ software can chat with many people at the same time, we use Eclipse to develop code can also compile code, tomcat can serve multiple users. Two: The realization way of multithreading

1: Bare Thread
The most basic way to implement threads is not to do too much explaining.
Extends Thread
Implements Runnable
Implements callable

The difference between runnable and callable is that
(1) The method prescribed by callable is call (), and the Runnable method is run ().
(2) A callable task can return a value after execution, and Runnable's task is not to return a worthwhile
(3) Call method can throw an exception, the Run method can not
(4) Running the callable task can get a future object that represents the result of an asynchronous computation.
It provides a way to check whether the calculation is complete, to wait for the calculation to complete, and to retrieve the results of the calculation.
The future object enables you to understand the execution of tasks, to cancel the execution of tasks, and to obtain execution results.

Talk is cheap, show me the code. (Less nonsense, put the code over.) O (∩_∩) o~)

Import java.util.ArrayList;
Import java.util.concurrent.Callable;
Import java.util.concurrent.ExecutionException;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.Future;
    public class Callabletest implements callable<string>{private int id;
    public callabletest (int id) {this.id = ID;  
    @Override public String called () throws Exception {return ' result of callabletest ' + ID; public static void Main (string[] args) throws Interruptedexception, executionexception {Executorservice ex
        EC = Executors.newcachedthreadpool (); 
        arraylist<future<string>> results = new arraylist<future<string>> ();
        for (int i = 0; i < i++) {Results.add (Exec.submit (New Callabletest (i))); for (future<string> fs:results) {if (Fs.isdone ()) {System.out.println (FS.G
           ET ()); else {System.out.println ("Future result isn't yet complete");
    } exec.shutdown ();
 }

}

2:executors Create a thread pool
Sun in Java5, Java thread of the class library to do a large number of extensions, where the thread pool is one of the new features of JAVA5, in addition to the thread pool, there are many multi-threaded-related content, for multithreaded programming has brought great convenience. In order to write efficient, stable and reliable multithreaded programs, the new contents of the thread section are particularly important.

Four types of thread pools:
(1) Newcachedthreadpool
Creates a cacheable thread pool that, if the thread pool length exceeds processing needs, is flexible enough to reclaim idle threads and, if not recyclable, create a new thread.
(2) Newfixedthreadpool
Creates a fixed-line pool that controls the maximum number of concurrent threads, and the threads that are exceeded wait in the queue.
(3) Newscheduledthreadpool
Create a fixed-line pool that supports timed and recurring task execution.
(4) Newsinglethreadexecutor creates a single-threaded thread pool that performs tasks with only a single worker thread, ensuring that all tasks are performed in the specified order (FIFO, LIFO, priority).

3:forkjoinpool Fork/join (forked/Combined) concurrent framework
JDK7 has added the Concurrency Framework-fork/join Framework, in which Forkjointask represents a task that needs to be performed, and the threads that actually perform those tasks are placed in a thread pool (forkjoinpool). Forkjoinpool is a excuteservice that can perform forkjointask, unlike Excuteservice, which takes a work-stealing pattern: all threads in the pool try to perform subtasks created by other threads. This makes it very rare that threads are idle and very efficient.

4:actor model

Actor, can be regarded as an independent entity, there is no connection between them. However, they can communicate through messages. After a actor receives other actor information, it can make various corresponding according to the need. The type of the message can be arbitrary, and the contents of the message can be arbitrary. This is a bit like webservice. Provide only interface services, you don't have to understand how I do it.

A actor how to handle multiple actor requests. It builds a message queue, which is queued every time it receives a message, and it takes out the message body from the queue each time. Usually we all make the process loop. Allow actor to handle the messages sent at all times.

Actor model = data + behavior + message.

The internal state of the actor model is maintained by its own behavior, the external thread cannot invoke the behavior of the object directly, the behavior must be triggered by the message, so that the internal data of the actor can only be modified by itself. Three: Threading Examples

Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;  
        public class Runnabletest implements Runnable {protected int countdown = 10;  
        private static int taskcount = 0;  

        private final int id = taskcount++; Public runnabletest () {} public runnabletest (int countdown) {This.countdown = Countd  
        Own Public String status () {return "#" + ID + "(+ (Countdown > 0?) Countdown: "liftoff!")  
        + ")"; @Override public void Run () {while (countdown--> 0) {SYSTEM.O  
                Ut.print (status ());  
                Thread.yield ();
                try {thread.sleep (1000);
                catch (Interruptedexception e) {e.printstacktrace ();  
        } System.out.println (); public static void Main (string[)args) {Executorservice exec = Executors.newfixedthreadpool (1);  
            for (int i = 0; i < 5; i++) {Exec.execute (New runnabletest ());  
        } exec.shutdown (); }  

}

If Executors.newfixedthreadpool (1); Execution results are

#0 (9) #0 (8) #0 (7) #0 (6) #0 (5) #0 (4) #0 (3) #0 (2) #0 (1) #0 (liftoff!)
#1 (9) #1 (8) #1 (7) #1 (6) #1 (5) #1 (4) #1 (3) #1 (2) #1 (1) #1 (liftoff!)
#2 (9) #2 (8) #2 (7) #2 (6) #2 (5) #2 (4) #2 (3) #2 (2) #2 (1) #2 (liftoff!)
#3 (9) #3 (8) #3 (7) #3 (6) #3 (5) #3 (4) #3 (3) #3 (2) #3 (1) #3 (liftoff!)
#4 (9) #4 (8) #4 (7) #4 (6) #4 (5) #4 (4) #4 (3) #4 (2) #4 (1) #4 (liftoff!)

If Executors.newfixedthreadpool (5); Execution results are

#1 (9) #0 (9) #2 (9) #3 (9) #4 (9) #0 (8) #2 (8) #1 (8) #3 (8) #4 (8) #3 (7) #2 (7) #4 (7) #1 (7) #0 (7) #1 (6) #2 (6) #4 (6) #0 (6) #3 (6) #1 (5) #4 (5) #3 (5) #2 (5) #0 (5) #1 (4) #4 (4) #3 (4) #2 (4) #0 (4) #1 (3) #2 (3) #4 (3) #3 (3) #0 (3) #1 (2) #4 (2) #3 (2) #0 (2) #2 (2) #1 (1) #3 (1) #4 (1) #2 (1) #0 (1) #1 (liftoff!) #4 (liftoff!) #2 (liftoff!) #0 (liftoff!) #3 (liftoff!)

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.