Java.util.Executor and Java.util.ArrayList

Source: Internet
Author: User

1, Java.util.ArrayList

2. The executor thread pool provides four methods for asynchronous execution.

Newcachedthreadpool creates a thread pool that can be cached, and if the thread pool length exceeds the processing needs, you can flexibly reclaim the idle thread, and if it is not recyclable, you can create a new thread.

Newfixedthreadpool creates a thread pool that can control the maximum number of concurrent threads, and the excess threads wait in the queue.

Newscheduledthread creates a fixed-line pool that supports timing and its periodic task execution.

Newsinglethreadexecutor creates a single thread pool that performs tasks only for the only worker thread. (Advanced first Out)

Package com. Simple;

Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;

Class Simplerunner implements Runnable
{
int runindex = 0;

public void Setrunindex (int runindex)
{
This.runindex = Runindex;
}

public void Run ()
{
Try
{
At random time in 3 seconds.
Thread.Sleep ((Long) (Math.random () * 3000));
System.out.println ("Start run:" + Runindex);
} catch (Interruptedexception e)
{
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}


The test class then uses Executorservice to execute asynchronously

public class Simplesync
{
An actuator that can hold 10 threads.
Final static Executorservice exec = Executors.newfixedthreadpool (10);

public static void Main (string[] args)
{
System.out.println ("Start first SYNC program.");

Put in 10 threads and run in parallel
for (int i = 0; i <; i++)
{
Simplerunner runner = new Simplerunner ();
Runner.setrunindex (i);
Exec.submit (runner);
}

Exec.shutdown ();//Shutdown Actuator

System.out.println ("Finish first SYNC program.");
}
}

Java.util.Executor and Java.util.ArrayList

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.