implements Runnable synchronized代码块 * 2个线程向同一数组中加随机数,每个数组加3个数,交替

package com.heima.lei;

import java.util.Random;

import javax.swing.plaf.SliderUI;

public class Test02 {

    /**implements Runnable synchronized代码块 * 2个线程向同一数组中加随机数,每个数组加3个数,交替 * @param args */
    public static void main(String[] args) {
      Thread t1 = new ThreadArray2();
      Thread t2 = new ThreadArray2();
      t1.setName("第一个线程:");
      t2.setName("第二个线程:");
      t1.start();
      t2.start();
    }

}
class ThreadArray2 extends Thread {
    private static final int []arr = new int [20];
    private static int j=0;
    public void run(){
        for(int i = 0;i < 3 ;i++){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {

                e.printStackTrace();
            }
            try {
                AddArray();
            } catch (InterruptedException e) {

                e.printStackTrace();
            }
        }
    }

    public  void AddArray() throws InterruptedException {
        synchronized (ThreadArray2.class) {
            Random r = new Random();
            int num = r.nextInt(100);
            arr[j] = num;
            System.out.println(Thread.currentThread().getName()+"arr["+j+"]="+num);
            j++;

        }
    }

}

你可能感兴趣的:(implements Runnable synchronized代码块 * 2个线程向同一数组中加随机数,每个数组加3个数,交替)