定义一个数组,大小为10;两个线程,都向这个数组中存放数据,当数组满时要求能够提示

package com.lzy.thread;

public class PeriodicWork03 {
	public static void main(String[] args) {
		Array a=new Array();
		new Thread(a,"线程一:").start();
		new Thread(a,"线程二").start();
	}
	
}
class Array implements Runnable{
int[] a=new int[10];
int i=0;
boolean flag=true;
	@Override
	public void run() {
		while(flag) {
		try {
			Thread.sleep(200);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		test();
		}
		
	}
	public synchronized void test() {
		if(i>9) {
			System.out.println("数组已满");
			flag=false;
			return;
		}
		try {
			Thread.sleep(200);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
			a[i]=i;
			i++;
			System.out.println(Thread.currentThread().getName()+"存放了:"+i);
	
	}
}
	


©️2020 CSDN 皮肤主题: 数字50 设计师:CSDN官方博客 返回首页