【问题标题】:How can I synchronize a block/method in Java while using parallel TestNG methods?如何在使用并行 TestNG 方法时同步 Java 中的块/方法?
【发布时间】:2020-08-19 15:45:26
【问题描述】:

假设我有以下 sn-p (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>

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

【问题讨论】:

    标签: java multithreading junit synchronization testng


    【解决方案1】:

    尝试锁定静态对象

    包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);
      }
    }
    

    }

    【讨论】:

    • 嗯,我明天试试,它应该可以在测试类中使用静态对象。
    猜你喜欢
    • 2022-12-10
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多