Why multithreading uses while to determine the condition without using the IF.

Source: Internet
Author: User

One, the code:

1  PackageZz.produceandconsumer;2 3 Importjava.util.LinkedList;4 5  Public classStorage {6     7     Private Final Static intmax_num=100;8     9     Private volatileLinkedlist<object> list=NewLinkedlist<object>();Ten      One      Public voidProduce (intpnum) { A         synchronized(list) { -             if(List.size () +pnum>max_num) { -System.out.println ("Current Product Quantity:" +list.size () + ", to produce quantity:" +pnum+ ", exceeding maximum Capacity:" +max_num+ "."); the                 Try { - list.wait (); -}Catch(interruptedexception e) { - e.printstacktrace (); +                 } -             } + //While (List.size () +pnum>max_num) { A //System.out.println ("Current number of Goods:" +list.size () + ", to produce quantity:" +pnum+ ", exceeding the maximum capacity" +max_num+ "); at //try { - //list.wait (); - //} catch (Interruptedexception e) { - //e.printstacktrace (); - //                } - //            } in             intI=0; -              while(i<pnum) { toSYSTEM.OUT.PRINTLN ("Want to produce:" +pnum+ ", List.size:" +list.size () + ", Maximum:" +max_num+ ", I:" +i); +List.add (NewObject ()); -i++; the             } *System.out.println ("produced" +pnum+ "goods, Warehouses in Inventory" +list.size () + "."); $ List.notifyall ();Panax Notoginseng         } -     } the      +      Public voidConsumerintcNum) { A         synchronized(list) { the //if (cnum>list.size ()) { + //System.out.println ("Current number of Goods:" +list.size () + ", to consume Quantity:" +cnum+ ", insufficient quantity."); - //try { $ //list.wait (); $ //} catch (Interruptedexception e) { - //e.printstacktrace (); - //                } the //            } -              while(cnum>list.size ()) {WuyiSystem.out.println ("Current Product Quantity:" +list.size () + ", to consume Quantity:" +cnum+ ", insufficient quantity."); the                 Try { - list.wait (); Wu}Catch(interruptedexception e) { - e.printstacktrace (); About                 } $             } -             intI=0; -             if(cnum>list.size ()) { -SYSTEM.OUT.PRINTLN ("Error"); A             } +              while(i<cNum) { the //System.out.println ("Size:" +list.size () + ", I:" +i+ ", CNum:" +cnum "); - List.remove (); $i++; the             } theSystem.out.println ("Consumption of" +cnum+ "goods, Warehouses in Inventory" +list.size () + "."); the List.notifyall (); the         } -     } in  the}
View Code
1  PackageZz.produceandconsumer;2 3  Public classProducerImplementsrunnable{4     5     PrivateStorage Storage;6     Private intnum;7     8Producer (Storage Storage,intnum) {9          This. storage=storage;Ten          This. num=num; One     }     A      -      Public voidProduce () { -          This. Storage.produce (num); the     } -      -      - @Override +      Public voidrun () { - produce (); +     } A}
View CodeView Code
1  PackageZz.produceandconsumer;2 3  Public classMain {4      Public Static voidMain (string[] args) {5Storage storage=NewStorage (); 6         7         NewThread (NewProducer (Storage, 22) . Start ();8         NewThread (NewProducer (Storage, 11) . Start ();9         NewThread (NewConsumer (storage,33) . Start ();Ten          One         NewThread (NewConsumer (Storage, 40) . Start ();  A         NewThread (NewConsumer (Storage, 50) . Start (); -         NewThread (NewProducer (Storage, 90) . Start (); -          the         NewThread (NewProducer (Storage, 65) . Start (); -     } -  -}
View Code

Second, the operation result:

More than 2.1 runs, you can see the results:

To produce: 90,list.size:151, Max: 100,i:86
To produce: 90,list.size:152, Max: 100,i:87
To produce: 90,list.size:153, Max: 100,i:88
To produce: 90,list.size:154, Max: 100,i:89
Production of 90 commodities, warehouse inventory of 155.
Consumption of 40 commodities, warehouse inventory of 115.
Consumption of 50 commodities, warehouse inventory of 65.

The list.size is greater than the maximum value we set for 100.

2.2 Note The 31 lines of code in the storage, let go of the 63 lines of code and open the IF in consumer, turn off while; Comment out the 15 lines of code in main and run the result multiple times:

    

Size:11,i:29,cnum:33
Size:10,i:30,cnum:33exception in Thread "Thread-3" java.util.NoSuchElementException
At Java.util.LinkedList.removeFirst (linkedlist.java:268)
At Java.util.LinkedList.remove (linkedlist.java:683)
At Zz.produceandconsumer.Storage.consumer (storage.java:64)
At Zz.produceandconsumer.Consumer.consume (consumer.java:19)
At Zz.produceandconsumer.Consumer.run (consumer.java:24)
At Java.lang.Thread.run (thread.java:745)

Size:9,i:31,cnum:33
Size:8,i:32,cnum:33
Consumption of 33 commodities, warehouse inventory of 7.

Iii. Analysis and conclusions:

If judged, when the next time slice is rotated to the thread, the record point of the thread may have been judged after the if condition, so the execution begins after the IF statement.

This causes the array to exceed the maximum length and to delete the empty elements of the error.

Reference: http://www.oschina.net/question/1245392_163830

  

  

  

Why multithreading uses while to determine the condition without using the IF.

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.