Search code examples
javamultithreadingswingconcurrencyjava.util.concurrent

How do I create a new instance of thread multiple times in same program


I am a newbie please forgive me if I am not clear with what I want. I have a java app which inserts into 2 mysql tables upon clicking submit, one is the on the local machine and other on the web server . The problem is I have created two Threads , one for each . It works fine the first time the app is launched and started , but when the app is running and i try to insert again by clicking submit , it does not do anything . Again when I restart the app it works fine for the first time . my question is how do I stop the thread or end and start a new instance of it , in the same instance of my app.

Am sorry if am not clear .

heres the code,

  final int m = MSfuntion.getmemomoc();

 Thread t1 = new Thread(new Runnable(){
 public void run()
 { 
while(runt1){

try{
        for(int i=0;i<=jTable2.getRowCount();i++)
            {
                Object slno= jTable2.getValueAt(i, 1);
                Object item2=  jTable2.getValueAt(i, 2);
                Object size2= jTable2.getValueAt(i, 3);

                String it = slno.toString();
                String si = item2.toString();
                int qt = Integer.parseInt(size2.toString());

                MSfuntion.saledetails(m,it, si, qt);
                //MSfuntion.saledetailsweb(m,it, si, qt);
                sc=0;
            }
        }catch(Exception e)
        {
        e.printStackTrace();
        }
    runt1=false;

   }
  }

});
 Thread t2 = new Thread(new Runnable(){

 public void run()
{ 
while(runt2){

 try{
        for(int i=0;i<=jTable2.getRowCount();i++)
            {
                Object slno= jTable2.getValueAt(i, 1);
                Object item2=  jTable2.getValueAt(i, 2);
                Object size2= jTable2.getValueAt(i, 3);

                String it = slno.toString();
                String si = item2.toString();
                int qt = Integer.parseInt(size2.toString());

                //MSfuntion.saledetails(m,it, si, qt);
                MSfuntion.saledetailsweb(m,it, si, qt);
                sc=0;
            }
        }catch(Exception e)
        {
        e.printStackTrace();
        }
    runt2=false;
       }
     t1.start();
     t2.start()

Solution

  • It doesn't sound like a threading issue to me. It sounds like you don't commit the write or release the database connection after you write the data into both tables. Depending on how you write the data to the database, it can happen that it works with one Thread, but not if you do it from multiple threads. When you run it the first time, the first thread locks the database and the Thread that is created for the second write, can't write data because the first thread didn't release the lock.

    One other thing, instead of spawning two threads every time someone clicks the button, it would be much better to use an ExecutorService