Write your own thread pool

Source: Internet
Author: User
Tags volatile

One, the line Cheng code is as follows

1. Blocking Task Queue Blockingqueue

Public interface Blockingqueue<e> {
Boolean offer (e e);
Public E take ();
}

Blocking task queue Implementation class Linkedblockingqueue

Import Java.util.concurrent.atomic.AtomicInteger;

Public class Linkedblockingqueue<e> implements blockingqueue<e> {
Private final atomicinteger count = New Atomicinteger ();
Private final int capacity;  

Transient node<e> head;
private transient node<e> last;    

Public linkedblockingqueue (int capacity) {
This.capacity = capacity;
last = head = new node<e> (null);
}
//Add a task to the end of the blocking queue
@Override
Public boolean offer (E e) {
//If the capacity of the queue has been reached, reject add, return false
if (    Count.get () = = capacity) {
return false;
}
Node<e> Node = new node<e> (E);
Last = last.next = node;
Count.getandincrement ();
return true;
}

Remove a task from the head of the blocking queue
@Override
Public E take () {
node<e> h = head.next;
if (h = = null) {
return null;
}
E x = H.item;
Head = h;
return x;
}

Static Class node<e>{
E item;
Node<e> Next;

Node (E x) {
item = x;
}
}
}

2, create the thread factory Threadfactory

Public interface Threadfactory {
Thread Newthread (Runnable R);
}

To create a factory implementation class for a thread mythreadfactory

Import Java.util.concurrent.atomic.AtomicInteger;

public class Mythreadfactory implements Threadfactory {
Private final Atomicinteger threadnumber = new Atomicinteger (1);

@Override
Public Thread Newthread (Runnable r) {
Thread t = new Thread (R, "demo" + Threadnumber.getandincrement ());
return t;
}
}

3. Thread Pool Interface Executorservice

Public interface Executorservice {
void execute (Runnable command);
}

Thread pool Implementation class Threadpoolexecutor

Import Java.util.HashSet;
Import Java.util.concurrent.atomic.AtomicInteger;

public class Threadpoolexecutor implements executorservice{
Private final hashset<worker> workers = new hashset<worker> ();
private static final Atomicinteger ctl = new Atomicinteger (0);

Private final blockingqueue<runnable> WorkQueue;
private volatile threadfactory threadfactory;
private volatile int corepoolsize;
private volatile int maximumpoolsize;

Public threadpoolexecutor (int corepoolsize,
int Maximumpoolsize,
Blockingqueue<runnable> WorkQueue,
Threadfactory threadfactory) {
This.corepoolsize = corepoolsize;
This.maximumpoolsize = maximumpoolsize;
This.workqueue = WorkQueue;
This.threadfactory = threadfactory;
}

@Override
public void Execute (Runnable command) {
If the thread pool is less than the number of core threads, call the Addworker method to add a worker thread
if (Ctl.get () < corepoolsize) {
if (Addworker (command, True)) {
Return
}
}
Otherwise, try to add the task to the task queue
if (workqueue.offer (command)) {
Workqueue.offer (command);
}else{//if adding the task to the task queue fails, the task queue is full, and the new open thread executes the task
If the new open thread fails
if (!addworker (command, false)) {
SYSTEM.OUT.PRINTLN ("task" + Command + "rejected by thread pool");
}
}
}

Private Boolean Addworker (Runnable Firsttask, Boolean core) {
int c = Ctl.get ();
if (c >= (core corepoolsize:maximumpoolsize)) {
return false;
}
Ctl.compareandset (c, c+1);

Worker W = new Worker (Firsttask);
Final Thread t = w.thread;
Workers.add (w);
T.start ();

return true;
}

Private Final class Worker implements runnable{
Final thread thread;
Runnable Firsttask;

Worker (Runnable firsttask) {
This.firsttask = Firsttask;
This.thread = Threadfactory.newthread (this);
}

@Override
public void Run () {
Runnable task = This.firsttask;
while (task! = NULL | | (Task = Workqueue.take ()) = null) {
Task.run ();
task = null;
}
}
}
}

4. Create a thread pool tool class executors

public class Executors {
public static Executorservice newfixedthreadpool (int nthreads) {
return new Threadpoolexecutor (Nthreads, Nthreads, New linkedblockingqueue<runnable> (2), New Mythreadfactory ());
}
}

Second, the test thread pool function

public class ThreadTest {
public static void Main (string[] args) {
/**
* 1. Create a thread pool using executors
*/
Executorservice executors = Executors.newfixedthreadpool (2);
/**
* 2, direct new threadpoolexecutor, and specify Corepoolsize and Maximumpoolsize not the same
*/
Executorservice executors = new Threadpoolexecutor (2, 4,
New Linkedblockingqueue<runnable> (3), New Mythreadfactory ());

Executors.execute (New Runnable () {
@Override
public void Run () {
int i = 0;
while (i++ < 5) {
System.out.println (Thread.CurrentThread (). GetName () + "--111");
try {
Thread.Sleep (5000);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
});
Executors.execute (New Runnable () {
@Override
public void Run () {
int i = 0;
while (i++ < 5) {
System.out.println (Thread.CurrentThread (). GetName () + "--222");
try {
Thread.Sleep (5000);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
});
Executors.execute (New Runnable () {
@Override
public void Run () {
int i = 0;
while (i++ < 5) {
System.out.println (Thread.CurrentThread (). GetName () + "--333");
try {
Thread.Sleep (5000);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
});
Executors.execute (New Runnable () {
@Override
public void Run () {
int i = 0;
while (i++ < 5) {
System.out.println (Thread.CurrentThread (). GetName () + "--444");
try {
Thread.Sleep (5000);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
});
Executors.execute (New Runnable () {
@Override
public void Run () {
int i = 0;
while (i++ < 5) {
System.out.println (Thread.CurrentThread (). GetName () + "--555");
try {
Thread.Sleep (5000);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
});
Executors.execute (New Runnable () {
@Override
public void Run () {
int i = 0;
while (i++ < 5) {
System.out.println (Thread.CurrentThread (). GetName () + "--666");
try {
Thread.Sleep (5000);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
});
Executors.execute (New Runnable () {
@Override
public void Run () {
int i = 0;
while (i++ < 5) {
System.out.println (Thread.CurrentThread (). GetName () + "--777");
try {
Thread.Sleep (5000);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
});
Executors.execute (New Runnable () {
@Override
public void Run () {
int i = 0;
while (i++ < 5) {
System.out.println (Thread.CurrentThread (). GetName () + "--888");
try {
Thread.Sleep (5000);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
});

System.out.println ("Main function End");
}
}

As can be seen from the output, 4 threads have been started, and the thread has performed multiple tasks and a task has been rejected.

Write your own thread pool

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.