Advertisement
Guest User

Untitled

a guest
Jan 20th, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.47 KB | None | 0 0
  1. package zad3;
  2.  
  3. public class TextsStandard {
  4.     boolean newTxt = false;
  5.     String txt = null;
  6.     volatile boolean isFirstDone = false;
  7.     long timeStart = 0;
  8.     long timeEnd = 0;
  9.  
  10.     synchronized String getText() {
  11.         while (newTxt == false)
  12.             try {
  13.                 wait();
  14.             } catch (InterruptedException e) {
  15.                 e.printStackTrace();
  16.             }
  17.         newTxt = false;
  18.         notifyAll();
  19.         return txt;
  20.     }
  21.  
  22.     synchronized void setText(String s) {
  23.         while (newTxt == true)
  24.             try {
  25.                 wait();
  26.             } catch (InterruptedException e) {
  27.                 e.printStackTrace();
  28.             }
  29.         newTxt = true;
  30.         txt = s;
  31.         notifyAll();
  32.     }
  33.  
  34.     public void start() {
  35.         timeStart = System.nanoTime();
  36.     }
  37.  
  38.     public void finish() {
  39.         timeEnd = System.nanoTime();
  40.         System.out.println("Czas ze standardową synchronizacją (w nanosekundach): " + new Long(timeEnd - timeStart));
  41.     }
  42.  
  43. }
  44.  
  45. public class StandardA extends Thread {
  46.     TextsStandard texts=null;
  47.     public StandardA()
  48.     {
  49.         texts=new TextsStandard();
  50.     }
  51.     @Override
  52.     public void run() {
  53.         new StandardB(texts).start();
  54.         texts.start();
  55.         for (int i=0;i<1000;i++)
  56.         {
  57.             texts.setText("a");
  58.         }
  59.         texts.isFirstDone=true;
  60.         synchronized(System.out) {
  61.         System.out.println(texts.isFirstDone); 
  62.         }
  63.     }
  64.    
  65. }
  66.  
  67. public class StandardB extends Thread {
  68.     TextsStandard texts = null;
  69.  
  70.     public StandardB(TextsStandard input) {
  71.         texts = input;
  72.     }
  73.  
  74.     @Override
  75.     public void run() {
  76.         while (texts.isFirstDone == false) {
  77.             texts.getText();
  78.         }
  79.  
  80.         texts.finish();
  81.     }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement