繁体   English   中英

如何在Java中创建两个线程之间的竞争状况?

[英]How to create a race situation between two threads in Java?

我想测试用作ID计数器的同步方法。 为了测试由给定方法返回的ID的唯一,我要创建两个线程之间的竞争局面谁将使给定方法的调用在同一时间 请问我该如何实现?

class Counter{
    private static int nextId = 1;
    public static synchronized int nextId() {
        int id = nextId;
        nextId += 1;
        return id;
    }
}

无法在发布的代码上创建竞争条件。 可变的共享状态是私有静态nextId变量,它由类实例的内部锁保护。 没有两个线程可以输入同步的nextId方法,因此无法出现竞争条件。

您可以执行以下操作来创建两个线程,并使它们从Counter类获取新的ID:

Thread t1= new Thread(){
    public void run(){
      for(int i=0; i<1000; i++){
          System.out.println("T1: "+Counter.nextId());
      }
    }
  }

  t1.start();

Thread t2= new Thread(){
    public void run(){
      for(int i=0; i<1000; i++){
          System.out.println("T2: "+Counter.nextId());
      }
    }
  }

  t2.start();

这将产生竞争条件。多次运行该程序。在大多数情况下每次都会在最后一次给出不同的结果。这仅适用于Java版本1.8或1.8 +。对于低于1.8版本的Java版本,请使用Runnable匿名类lambda表达式。

       public class Main {
   public static void main(String[] args) {
        new Thread(()-> {
            Random rand = new Random();
            for(int i=0;i<1000;i++) {
                System.out.println(Counter.nextId());
                try {
                    Thread.sleep(rand.nextInt(10));
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(()-> {
            Random rand = new Random();
            for(int i=0;i<1000;i++) {
                System.out.println(Counter.nextId());
                try {
                    Thread.sleep(rand.nextInt(10));
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
class Counter{
private static int nextId = 1;
public static  int nextId() {
    int id = nextId;
    nextId += 1;
    return id;
 }
}   

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM