我对多线程非常陌生。我目前正在处理一个项目,该项目需要启动一个线程,完成后通知启动它的线程并继续执行。我尝试使用一个布尔变量,并指示系统打印出一些字符串来指示操作的阶段。查找下方的代码
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!");
}
}
}
尝试在主线程中调用join()
,如下所示:
mainThread.join()
它将等待其他线程完成,然后主线程继续执行。
但是尝试使用其他多线程技术,如CountDownLatch
、Barrier
或Cyclic
。