Declare a shared array, up to two threads, two threads at a time (you can write a random number), add data to the array, and each thread adds 3 data to the group. __java Advanced Practice

Source: Internet
Author: User
Package com.heima.test;

Import Java.util.Random;
     public class Test11 {/** declares a shared array, up to two threads, two threads at intervals (can write a random number), adds data to the array, and each thread adds 3 data to the group.
        * @param args */public static void main (string[] args) {Thread T1 = new Mythread ();
        Thread t2 = new Mythread (); T1.setname ("First thread.")
        "); T2.setname ("Second thread").
        ");
        T1.start ();
    T2.start ();
    } class Mythread extends thread{private static int arr[] = new INT[6];
    private static int j = 0; public void Run () {for (int i = 0;i < 3; i++) {try {Thread.
                    Sleep (1000);
                    catch (Interruptedexception e) {e.printstacktrace ();
                } addarray ();
            } public void AddArray () {synchronized (mythread.class) {Random r = new Random ();
            int num = r.nextint (100) +1; ARR[J] = nUm
            System.out.println (Thread.CurrentThread (). GetName () + "arr[" +j+ "]=" +num);
        j + +; }


    }
}

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.