qq_39494095
qq_39494095
2019-05-03 17:31

为什么每个线程输出的counter大小不一,先输出的可能比后输出的要大?

  • java
  • intellij-idea

在用多线程去测试race condition的时候,出现了前后输出但总次数大小不一的情况,最关键大小不是增序而是无序。求大神解答!谢谢!

package ThreadTry;

import java.util.Scanner;

/**
 * Created by Administrator on 2019/5/2 0002.
 */
public class Homework {
    public static void main(String args[]) throws InterruptedException {
        Th th1,th2,th3,th4,th5;
        System.out.println("请设定每个线程的睡眠时间(ms):");
        Scanner reader=new Scanner(System.in);
        int t=reader.nextInt();
        Th.setTime(t);
        Th th=new Th();
        Thread thread1,thread2,thread3,thread4,thread5,thread6,thread7,thread8,thread9,thread10;
        thread1=new Thread(th);
        thread1.setName("线程1");
        thread2=new Thread(th);
        thread2.setName("线程2");
        thread3=new Thread(th);
        thread3.setName("线程3");
        thread4=new Thread(th);
        thread4.setName("线程4");
        thread5=new Thread(th);
        thread5.setName("线程5");
        thread6=new Thread(th);
        thread6.setName("线程6");
        thread7=new Thread(th);
        thread7.setName("线程7");
        thread8=new Thread(th);
        thread8.setName("线程8");
        thread9=new Thread(th);
        thread9.setName("线程9");
        thread10=new Thread(th);
        thread10.setName("线程10");
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        thread5.start();
        thread6.start();
        thread7.start();
        thread8.start();
        thread9.start();
        thread10.start();
        thread1.join();
        thread2.join();
        thread3.join();
        thread4.join();
        thread5.join();
        thread6.join();
        thread7.join();
        thread8.join();
        thread9.join();
        thread10.join();
        System.out.println("次数="+th.getCounters());
    }
}
class Th implements Runnable {
    int counter = 0;
    static int t = 0;

    static void setTime(int x) {
        t = x;
    }

    @Override
    public void run() {
        String name=Thread.currentThread().getName();
        for (int i = 0; i < 1000; i++) {
            counter++;
            try {
                Thread.sleep(t);
            }
            catch (InterruptedException e) {
            }
        }
        System.out.println("我是"+name+"次数="+counter);
    }
    int getCounters(){
        return counter;
    }
}

这个是输出结果:
图片说明

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答