如何在使用并行testng方法时同步java中的块/方法?

hzbexzde  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(401)

假设我有以下代码片段(testng):

package com.parallel;
import org.testng.annotations.Test;

public class TestParallelOne {

    @Test
    public void testCaseOne() {
        //Printing Id of the thread on using which test method got executed
        System.out.println("Test Case One with Thread Id:- "
                + Thread.currentThread().getId());
        test();
    }

    @Test
    public void testCaseTwo() {
        ////Printing Id of the thread on using which test method got executed
        System.out.println("Test Case two with Thread Id:- "
                + Thread.currentThread().getId());
        test();
    }

    public synchronized void test()
    {
        for(int i =0; < 10; i++) System.out.println(i);
    }
}

以及下面的suite.xml

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Parallel test suite" parallel="methods" thread-count="2">
  <test name="Regression 1">
    <classes>
      <class name="com.parallel.TestParallelOne"/>
    </classes>
  </test>
</suite>

我的期望是,测试将并行运行,但第一个获得锁的测试将保持它,直到它完成方法(与同步块的期望相同),但synchronized关键字被完全忽略。。。有什么问题吗?synchronized方法解决方案是针对我的特定情况的最佳解决方案,但似乎我缺少testng的一些东西?

nnvyjq4y

nnvyjq4y1#

尝试锁定静态对象
包com.parallel;
导入org.testng.annotations.test;
公共类testparallelone{

private static String LOCK = "lock";

@Test
public void testCaseOne() {
    System.out.println("Test Case One with Thread Id:- "  + 
    Thread.currentThread().getId());
    test();
}

@Test
public void testCaseTwo() {
    System.out.println("Test Case two with Thread Id:- "
            + Thread.currentThread().getId());
    test();
}

public void test()
{
    synchronized(LOCK){
    for(int i =0; < 10; i++) System.out.println(i);
  }
}

}

相关问题