package test01;
import java.util.Random;
public class Thread_Demo1 {
/**
* 数组里有5个元素,两个线程,怎么输出六次?
*/
public static void main(String[] args) {
MyRunnable mr = new MyRunnable();
Thread t1 = new Thread(mr);
Thread t2 = new Thread(mr);
t1.start();
t2.start();
}
}
class MyRunnable implements Runnable{
int[] arr = {1,2,3,4,5};
int b;
Random ra = new Random();
@Override
public void run() {
while(true){
synchronized (ra) {
if(b==6){
return;
}
System.out.println(Thread.currentThread().getName()+"输出了:"+arr[ra.nextInt(arr.length)]);
b++;
}
}
}
} |