- package com.itheima;
- import java.util.Random;
- public class Test2 {
- /**
- * 创建类,实现Runable接口,实现run方法
- * @param args
- */
- public static void main(String[] args){
- //开启两个线程,向数组中添加数据
-
- Thread thread1 = new Thread(new Demo(),"thread1");
- Thread thread2 = new Thread(new Demo(),"thread2");
-
- thread1.start();
- thread2.start();
- }
-
-
- public static class Demo implements Runnable{
- //共享数组
- String[] datas = new String[6];
-
- //添 加数据个数
- int position = 0;
-
-
- public void run(){
- //没一个线程添加数据的个数,计数器
- int count = 1;
- Random random = new Random();
-
- //没一个线程只添加3个数据
- while(count<=3){
- try{
- //通过sleep实现随机时间添加
- Thread .sleep(random.nextInt(2000));
-
- //实现代码同步
- synchronized(datas){
- //添加数据
- datas[position] = Thread.currentThread().getName()+"."+count;
- System.out.println("线程"+Thread.currentThread().getName()+"添加数据:"+count);
- count++;
- position++;
- }
- }catch (Exception e){
- e.printStackTrace();
- }
- }
- }
- }
-
- }
复制代码 |