Why doesn't my Java program write String into file?
<p>I have two Threads and each Thread should write its name and an increasing number into a file - but it doesn't work. </p>

<p>If i use the <code>System.out.println()</code> method the threads are working perfectly only the writing into the file does fail. Any idea why?</p>

<p>This is how my Threads look like:</p>

<pre><code>package ThreadTest;

import java.io.*;

public class Thread1 implements Runnable {

public void run() {
    int x = 0;
    while (true) {

        try {

            BufferedWriter p1 = new BufferedWriter(new FileWriter("C:\\Users\\User\\Desktop\\a1.txt"));
            x++;
            p1.write("Thread11: " + x);
            Thread.sleep(500);
            p1.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }
  }

}
</code></pre>

<p>The main class looks like this:</p>

<pre><code>package ThreadTest;

public class ThreadTestTest {

    public static void main(String args[]) {

        try {
            Thread1 t11 = new Thread1();
            Thread t1 = new Thread(t11);

            Thread2 t22 = new Thread2();
            Thread t2 = new Thread(t22);

            t2.start();
            t1.start();

            t1. join();
             t2. join();


        } catch (Exception e) {
            e.getMessage();
        }

    }

}
</code></pre>