fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone {
  9.  
  10. private int value;
  11.  
  12. public synchronized int getValue() {
  13. return this.value;
  14. }
  15.  
  16. public synchronized void setValue(int value) {
  17. this.value = value;
  18. }
  19.  
  20. public static void main(String[] args) {
  21.  
  22. Ideone nts = new Ideone();
  23.  
  24. Thread th1 = new Thread(new Runnable() {
  25. public void run() {
  26. nts.setValue(5);
  27. System.out.println("Thread Id " + Thread.currentThread().getId() + ", expected value is 5, value=" + nts.getValue());
  28. }
  29. });
  30.  
  31. Thread th2 = new Thread(new Runnable() {
  32. public void run() {
  33. nts.setValue(10);
  34. System.out.println("Thread Id " + Thread.currentThread().getId() + ", expected value is 10, value="
  35. + nts.getValue());
  36. }
  37. });
  38.  
  39. Thread th3 = new Thread(new Runnable() {
  40. public void run() {
  41. nts.setValue(15);
  42. System.out.println("Thread Id " + Thread.currentThread().getId() + ", expected value is 15, value="
  43. + nts.getValue());
  44. }
  45. });
  46.  
  47. th1.start();
  48. th2.start();
  49. th3.start();
  50. }
  51.  
  52. }
Success #stdin #stdout 0.04s 2315264KB
stdin
Standard input is empty
stdout
Thread Id 8, expected value is 5, value=5
Thread Id 9, expected value is 10, value=10
Thread Id 10, expected value is 15, value=15