fork download
  1. import java.io.FileWriter;
  2. import java.io.IOException;
  3.  
  4. /**
  5.  * Created by IP44 on 25.11.2016.
  6.  */
  7. class Synchro {
  8. public Synchro() throws IOException {
  9. }
  10.  
  11. public synchronized void writing(String str, int i) {
  12. try {
  13. System.out.print(str + i);
  14. Thread.sleep((long)(Math.random() * 50));
  15. System.out.println("->" + i + " ");
  16. } catch (Exception e) {
  17. System.err.print("Error of stream");
  18. e.printStackTrace();
  19. }
  20. }
  21. }
  22.  
  23. class MyThread extends Thread {
  24. private Synchro s;
  25.  
  26. public MyThread(String str, Synchro s) {
  27. super(str);
  28. this.s = s;
  29. }
  30. public void run() {
  31. try {
  32. for (int i = 0; i < 5; i++) {
  33. s.writing(getName(), i);
  34. Thread.sleep((long)(Math.random() * 50));
  35. }
  36. } catch (Exception ex) {
  37. ex.printStackTrace();
  38. }
  39. }
  40. }
  41.  
  42. class SynchroThreads {
  43. public static void main(String[] args) {
  44. try {
  45. Synchro s = new Synchro();
  46.  
  47. MyThread t1 = new MyThread("First", s);
  48. MyThread t2 = new MyThread("Second", s);
  49. t1.start();
  50. t2.start();
  51. t1.join();
  52. t2.join();
  53. } catch (Exception ex) {
  54. ex.printStackTrace();
  55. }
  56. }
  57. }
Success #stdin #stdout #stderr 0.05s 711168KB
stdin
Standard input is empty
stdout
First0->0 
Second0->0 
First1->1 
Second1->1 
First2->2 
Second2->2 
First3->3 
Second3->3 
First4->4 
Second4->4 
stderr
Java HotSpot(TM) Client VM warning: No monotonic clock was available - timed services may be adversely affected if the time-of-day clock changes