Java producer consumer (2)

Source: Internet
Author: User

I wrote a message in the forum today for netizens. I have already debugged one developer who corresponds to 20 consumers. The code is relatively casual. I didn't write classes separately. I used internal classes. if there is something wrong with that place, you are welcome to correct and criticize it.

Public class executorservicetest {
Private Static int maxtask = 80;
Private Static object lock = new object ();

Public static void main (string [] ARGs ){
Final list tasks = new arraylist ();
Final executorservice exec = executors. newcachedthreadpool ();
Exec.exe cute (New runnable (){
Public void run (){
While (! Thread. interrupted ()){
Try {
Synchronized (tasks ){
If (tasks. Size () = maxtask)
Tasks. Wait ();
}
Synchronized (LOCK ){
If (tasks. Size ()! = Maxtask ){
Tasks. Add (new object ());
System. Out. println ("production task ");
Lock. policyall ();
Thread. Yield ();
}
}
} Catch (interruptedexception e ){
E. printstacktrace ();
}
}
}
});
For (INT I = 0; I <20; I ++ ){
Exec.exe cute (New runnable (){
Public void run (){
While (! Thread. interrupted ()){
Try {
Synchronized (LOCK ){
If (tasks. Size () = 0)
Lock. Wait ();
}
Synchronized (tasks ){
If (tasks. Size ()> 0 ){
Tasks. Remove (0 );
System. Out. println ("Processing Task ");
Tasks. policyall ();
}
}
} Catch (interruptedexception e ){
E. printstacktrace ();
}
}
}
});
}
Exec. Shutdown ();
}
}

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.