我对多线程很新。我目前正在开发一个项目,该项目需要启动一个线程,并在完成时通知启动它的线程并继续执行。 我尝试使用布尔变量并指示系统打印出一些字符串以指示操作阶段。找到下面的代码
public class BankDatabaseSQL {
private Connection connection;
private ResultSet resultSet;
private static final String URL = "jdbc:mysql://localhost/banktesting";
private static final String USERNAME = "root";
Account account;
public final Object monitor = new Object();
private PreparedStatement setBalance;
private PreparedStatement getAccount;
int numberOfRows;
/** code omitted **/
/**
method in question
*/
public synchronized boolean authenticatePrint(){
try{
MainForm mainForm = new MainForm();
do{
ExecutorService threadExecutor = Executors.newCachedThreadPool();
mainForm.accNo = account.getAccountNumber();
threadExecutor.execute(mainForm);
wait();
}while(mainForm.verified = false); // while the verified variable of the mainForm object is set to false,
// the thread should keep waiting. The process has not gotten into this
// if statement.
if(mainForm.verified = true){
System.out.println("time to notify");
notify();
}
应该进行通知的第二种方法如下所示
public class MainForm extends JFrame implements Runnable
{
public void run() {
new MainForm();
}
public synchronized void onVerify() {
VerificationForm form = new VerificationForm(this);
form.setVisible(true);
System.out.println("\nTime to onVerify");
if(form.verificationStatus = true){
verified = true; // variable for the mainForm object to aid in notifying the thread
System.out.println("\nVerified = true has been set!");
}
}
}
答案 0 :(得分:0)
尝试在主线程中调用join()
,如下所示:
mainThread.join()
它将等待其他线程完成,然后主线程继续执行。
但尝试使用其他多线程技术,例如CountDownLatch
,Barrier
或Cyclic
。