1

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

1
  • synchronized keyword 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 define LOCK and use it as parameter to synchronized block. Commented Jun 3, 2019 at 7:48

1 Answer 1

1

You can use synchronized on the block where you want mutual exclusion. synchronized ensures only one thread will enter that block. It doesn't ensure the order. To maintain the order, you can use join() method. Here's is your modified code, where I'm just printing values instead of inserting into DB

package helper;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;

public class Test extends Thread {
  String a1 = "", b1 = "";

  public Test(String a, String b) {
    a1 = a;
    b1 = b;
  }

  Integer resource = new Integer(1);
  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();
       */
      synchronized (resource) {
        System.out.println(a1+" # "+b1 +" # "+Thread.currentThread().getName());
      }


    } catch (Exception e) {
      System.out.println(e);
    }
  }

  public static void main(String args[]) throws InterruptedException {
    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");
    Test obj;
    for (int i = 0; i < 5; i++) {
      obj = new Test(fname.get(i), lname.get(i));
      obj.start();
      obj.join();
      // try{
      // obj.join();
      // }catch(Exception e){System.out.println(e);}
    }
  }
}

output:

Vinoth # Kumar # Thread-0
Sesha # Janarthan # Thread-1
Sachin # Sabarish # Thread-2
Dinesh # Kumar # Thread-3
Karan # Kumar # Thread-4
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, but i am getting the output..but thread-1 is missing now..which means the op nis like thread-0 thread-2 ..etc
Ok, one system is showing properly and other is not. it is okay
can you help with the same output without using join() method
there's way, but ThreadScheduler doesn't take any guarantee of the order of execution of thread. you can set thread priority before starting the thread like - obj.setPriority(MAX_PRIORITY-i);
I tried executing it... not all the time it is synchronized

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.