Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

multithreading - 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('
');
                            
                            
                        }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('
');
                            
                            
                        }catch(Exception e)
                        {
                            System.out.println("eroare");
                        }
                  }
                  
                  
              }
            
                      );
              t1.start();
              t2.start();   
         myWriter.close();
        }catch(Exception e)  
        {  
            e.printStackTrace();  
            System.out.print("teapa frate 
"); 
        }

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
" , "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
" , "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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...