- public class Test21 implements Runnable{
- private int[] arr = new int[100];
- private int count = 0;
- public void run(){
- while(true){
- synchronized (this) {
- Thread.yield();
- for(int i=0;i<3;i++){//第二次循环进来,count应该是0啊?
- int num = (int)(Math.random()*5)+1;
- System.out.println(Thread.currentThread().getName()+"为数组第"+count+"个索引写入了"+num);
- count++;//第一次count从0自增为1
- if(count<arr.length){
- arr[count-1] = num;//为了索引从1-1变成0
- }else{
- return;
- }
- }
- }
- }
- }
- public static void main(String[] args) {
- Test21 mt = new Test21();
-
- Thread t1 = new Thread(mt);
- t1.setName("线程1");
- Thread t2 = new Thread(mt);
- t2.setName("线程2");
-
- t1.start();
- t2.start();
- }
- }
复制代码 |
|