Java multi-thread access Array

Source: Internet
Author: User
Public class test_runnable implements runnable {private string name; Private Static int next = 0; Private Static int Len = 10000; private final static int num = 5; private Static string STR [] = new string [Len]; Public test_runnable (string name) {super (); this. name = Name;} public test_runnable () {super (); // todo auto-generated constructor stub} public static void visit (string name) throws interruptedexception {While (hasnext ()) {system. out. println (STR [getnext ()] + "" + name); thread. sleep (1) ;}} public void run () {for (INT I = 0; I <4; I ++) {try {visit (this. name);} catch (interruptedexception e) {// todo auto-generated Catch Block E. printstacktrace () ;}}// index of the array element to be accessed next time public synchronized static int getnext () {next ++; return next-1 ;} // determine whether the access is complete. Public static Boolean hasnext () {If (next <Len) return true; return false;} public static void main (string [] ARGs) throws interruptedexception {for (INT I = 0; I <Str. length; I ++) // initialization character array {STR [I] = new string ("string" + I);} thread. sleep (1000); // create ten threads test_runnable tr [] = new test_runnable [num]; thread TD [] = new thread [num]; for (INT I = 0; I <tr. length; I ++) {tr [I] = new test_runnable ("Thread" + I); TD [I] = new thread (TR [I]);} long start = system. currenttimemillis (); thread. sleep (1000); // The thread starts executing the task for (INT I = 0; I <TD. length; I ++) {TD [I]. start ();} thread. sleep (2000); long end = system. currenttimemillis (); system. out. println (end-Start ));}}

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.