I have doubt in fetching my data from mysql table using synchronized threads, I tried using join(method), but I want to use synchronized keyword and need to get the same result. Please provide me the correct code by modifying mine. I did asynchronously.
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class SyncThread extends Thread{
String a1="", b1="";
public SyncThread(String a,String b)
{
a1=a;
b1=b;
}
public void run(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/EmployeeDetails","root","root");
PreparedStatement stmt=con.prepareStatement("insert into EmployeeDetail values(?,?,?)");
stmt.setString(1,a1);
stmt.setString(2,b1);
stmt.setString(3,Thread.currentThread().getName());
stmt.execute();
con.close();
}
catch(Exception e){ System.out.println(e);}
}
public static void main(String args[]){
List<String> fname=new ArrayList<String>();
fname.add("Vinoth");
fname.add("Sesha");
fname.add("Sachin");
fname.add("Dinesh");
fname.add("Karan");
List<String> lname=new ArrayList<String>();
lname.add("Kumar");
lname.add("Janarthan");
lname.add("Sabarish");
lname.add("Kumar");
lname.add("Kumar");
SyncThread obj;
for(int i=0;i<5;i++)
{
obj=new SyncThread(fname.get(i),lname.get(i));
obj.start();
// try{
// obj.join();
// }catch(Exception e){System.out.println(e);}
}
}
}
I expect the output of fname lname Thread-0 fname lname Thread-1 fname lname Thread-2 fname lname Thread-3 fname lname Thread-4
synchronizedkeyword doesn't guarantee you, that threads will be executed in the order they come to monitor (synchronized block). To execute them using synchronized - extract a required block to a separate method, where all threads share same Lock - for example make a static method, or explicitly defineLOCKand use it as parameter to synchronized block.