KensoFD
KensoFD

Reputation: 13

How can i print data in a file using 2 threads in java

i need to print some data in a file using 2 threads that run alternative, one for odd index, and the other for even index. The data i have is stored in this array, cursuri = new ArrayList(), that is created from

    String nume;
    String descriere;
    Profesor profu;
    Set <Student> studenti;
    int[] note;

The data i need is saved in studenti, and this is what i tried so far:

public String[] studentiEven(ArrayList<Curs> c)
    {
        synchronized (this) 
        {
            for(int i=0;i<c.size();i++)
            {
                String[] x= new String[3];
                int nr=0;
                for(Student s:c.get(i).studenti)
                {
                    while(nr%2==1)
                    {
                        try {
                            wait();
                        }catch(InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    nr++;
                    notify();
                    x[0]=s.nume;
                    x[1]=s.prenume;
                    x[2]=s.grupa;
                    return x;
                
                }
                
            }
            String[] y=new String[3];
            return y;
        }
    }
    
    public String[] studentiOdd(ArrayList<Curs> c)
    {
        synchronized (this) 
        {
            for(int i=0;i<c.size();i++)
            {
                String[] x= new String[3];
                int nr=0;
                for(Student s:c.get(i).studenti)
                {
                    while(nr%2==0)
                    {
                        try {
                            wait();
                        }catch(InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    nr++;
                    notify();
                    x[0]=s.nume;
                    x[1]=s.prenume;
                    x[2]=s.grupa;
                    return x;
                
                }
            }
            String[] y=new String[3];
            return y;
        }
    }

Those being 2 functions, and in the main i tried to write:

 try {
        FileWriter myWriter = new FileWriter("studenti555.txt");
            
        final String[] a = new String[3];
            Thread t1=new Thread(new Runnable() {
                  public void run()
                  {
                        a[0]=c.studentiEven(c.cursuri)[0];
                        a[1]=c.studentiEven(c.cursuri)[1];
                        a[2]=c.studentiEven(c.cursuri)[2];  
                        try {
                            myWriter.write(a[0]);
                            myWriter.write(',');
                            myWriter.write(a[1]);
                            myWriter.write(' ');
                            myWriter.write(a[2]);
                            myWriter.write('\n');
                            
                            
                        }catch(Exception e)
                        {
                            System.out.println("eroare");
                        }
                  }
                  
                  
              }
                      );
            Thread t2=new Thread(new Runnable() {
                  public void run()
                  {
                        a[0]=c.studentiOdd(c.cursuri)[0];
                        a[1]=c.studentiOdd(c.cursuri)[1];
                        a[2]=c.studentiOdd(c.cursuri)[2];   
                        try {
                            myWriter.write(a[0]);
                            myWriter.write(',');
                            myWriter.write(a[1]);
                            myWriter.write(' ');
                            myWriter.write(a[2]);
                            myWriter.write('\n');
                            
                            
                        }catch(Exception e)
                        {
                            System.out.println("eroare");
                        }
                  }
                  
                  
              }
            
                      );
              t1.start();
              t2.start();   
         myWriter.close();
        }catch(Exception e)  
        {  
            e.printStackTrace();  
            System.out.print("teapa frate \n"); 
        }

I tried to debug it, but it didn't go through the catch exception or anything, could you guys please help me out?

Upvotes: 0

Views: 270

Answers (2)

Mehdi
Mehdi

Reputation: 62

You can use semaphores to do this task

by setting odd semaphore and even semaphore to 1 and 0 respectively, at the beginning when both threads try to acquire the semaphore only odd semaphore let the thread to pass because it's initialized with 1. this way guarantees that the odd thread run before the even thread.

        FileWriter fileWriter = new FileWriter("./text.txt");
        Semaphore oddSem = new Semaphore(1);
        Semaphore evenSem = new Semaphore(0);
        List<Object> list = new ArrayList<>();

for odd thread, at first line try to acquire the oddSem and after getting one item from the list release the evenSem. this way even thread can now proceed.

        Runnable oddWriter = () -> {
            Object object;
            do {
                acquire(oddSem);
                if (list.isEmpty()) {
                    evenSem.release();
                    break;
                }
                object = list.remove(0);
                evenSem.release();
                String value = String.format("%s %s\n" , "Odd Thread:",object.toString());
                writeToFile(fileWriter, value);
            } while (true);
        };

for the even thread do the opposite

        Runnable evenWriter = () -> {
            Object object;
            do {
                acquire(evenSem);
                if (list.isEmpty()) {
                    oddSem.release();
                    break;
                }
                object = list.remove(0);
                oddSem.release();
                String value = String.format("%s %s\n" , "Even Thread:",object.toString());
                writeToFile(fileWriter, value);
            } while (true);
        };

and finally, start threads

        Thread oddThread = new Thread(oddWriter);
        Thread evenThread = new Thread(evenWriter);

        oddThread.start();
        evenThread.start();

        try {
            oddThread.join();
            evenThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        fileWriter.close();

Upvotes: 0

Andrea
Andrea

Reputation: 346

 t1.start();
 t2.start();   
 myWriter.close();

you close myWriter while t1 and t2 are running try with

 t1.start();
 t2.start();  
 t1.join();
 t2.join(); 
 myWriter.close();

Another problem is that both function studentiEven and studentiOdd call wait();. This stops execution till some other thread call notify() but there is no thread that call notify();

Notice also that final String[] a = new String[3]; is shared between t1 and t2 and this is not threadsafe.

Upvotes: 1

Related Questions