fork(1) download
  1. import java.io.FileWriter;
  2. import java.io.IOException;
  3.  
  4. class Synchro {
  5. private FileWriter fileWriter;
  6.  
  7. public Synchro(String file) throws IOException {
  8. fileWriter = new FileWriter(file, true);
  9. }
  10. public void close() {
  11. try {
  12. fileWriter.close();
  13. } catch (IOException e) {
  14. e.printStackTrace();
  15. }
  16. }
  17. public synchronized void writing(String str, int i) {
  18. try {
  19. System.out.print(str + i);
  20. fileWriter.append(str + i);
  21. Thread.sleep((long)(Math.random() * 50));
  22. System.out.print("->" + i + " ");
  23. fileWriter.append("->" + i + " ");
  24. } catch (IOException ex) {
  25. System.out.print("Error of reading");
  26. ex.printStackTrace();
  27. } catch (InterruptedException e) {
  28. System.err.print("Error of stream");
  29. e.printStackTrace();
  30. }
  31. }
  32. }
  33.  
  34. class MyThread extends Thread {
  35. private Synchro s;
  36.  
  37. public MyThread(String str, Synchro s) {
  38. super(str);
  39. this.s = s;
  40. }
  41. public void run() {
  42. for (int i = 0; i < 5; i++) {
  43. s.writing(getName(), i);
  44. }
  45. }
  46. }
  47.  
  48. public class SynchroThreads {
  49. public static void main(String[] args) {
  50. try {
  51. Synchro s = new Synchro("C:\\Users\\~\\Downloads\\data.txt");
  52.  
  53. MyThread t1 = new MyThread("First", s);
  54. MyThread t2 = new MyThread("Second", s);
  55. t1.start();
  56. t2.start();
  57. t1.join();
  58. t2.join();
  59. s.close();
  60. } catch (Exception ex) {
  61. ex.printStackTrace();
  62. }
  63. }
  64. }
  65.  
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
Java HotSpot(TM) Client VM warning: No monotonic clock was available - timed services may be adversely affected if the time-of-day clock changes
Main.java:48: error: class SynchroThreads is public, should be declared in a file named SynchroThreads.java
public class SynchroThreads {
       ^
1 error
stdout
Standard output is empty