我在类中编写了一个非静态同步方法,以避免多个线程同时更新 Excel 工作簿。例如,ID #9 和 #10 的线程正在尝试更新 Excel,预期 Thread#9 应该完成同步方法的操作,然后 Thread#10 应该能够调用我们没有发生的方法。下面是代码片段。
public synchronized boolean put(String parameterName, String parameterValue) {
try {
System.out.println("Start Time:= " + Thread.currentThread().getId() + " :: " + LocalDateTime.now().toString());
updateData(data.get("XLFileName"), data.get("XLSheetName"), parameterName, parameterValue, data.get("TestCaseID"), data.get("Iteration"));
System.out.println("End Time:= " + Thread.currentThread().getId() + " :: " + LocalDateTime.now().toString());
return true;
} catch (FilloException flex) {
flex.printStackTrace();
// extentTest.log(LogStatus.FATAL, "A", flex.getMessage());
return false;
}
}
public void updateData(String XLFileName, String XLSheet, String parameterName, String parameterValue, String testCaseID, String iteration) throws FilloException {
Fillo fillo = new Fillo();
Connection connection = fillo.getConnection(XLFileName);
String strQuery = "Update " + XLSheet + " Set " + parameterName + "='" + parameterValue + "' where TestCaseID = '" + testCaseID + "' and Iteration = '" + iteration + "'";
connection.executeUpdate(strQuery);
connection.close();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Current Output: Start Time:= 10 :: 2017-03-20T15:03:31.041 1 row(s) affected Start Time:= 9 :: 2017-03-20T15:03:31.619 1 row(s) affected End Time:= 10 :: 2017-03-20T15:03:41.201 End Time:= 9 :: 2017-03-20T15:03:41.675
Expected Output: Start Time:= 10 :: 2017-03-20T15:03:31.041 1 row(s) affected End Time:= 10 :: 2017-03-20T15:03:41.201 Start Time:= 9 :: 2017-03-20T15:03:31.619 1 row(s) affected End Time:= 9 :: 2017-03-20T15:03:41.675
也尝试过同步块(synchronized block)。
最佳答案
您可以尝试使用带锁的类同步块(synchronized block),如下所示。
public synchronized boolean put(String parameterName, String parameterValue) {
synchronized (DataBook.class) {
try {
System.out.println("Start Time:= " + Thread.currentThread().getId() + " :: " + LocalDateTime.now().toString());
updateData(data.get("XLFileName"), data.get("XLSheetName"), parameterName, parameterValue, data.get("TestCaseID"), data.get("Iteration"));
System.out.println("End Time:= " + Thread.currentThread().getId() + " :: " + LocalDateTime.now().toString());
return true;
} catch (FilloException flex) {
flex.printStackTrace();
return false;
}
}
}
关于java - 并行执行 : How to update Excel WorkBook using Synchronized method, 仅在同步方法执行完成后?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42900684/