Guest User

Untitled

a guest
Feb 24th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. public class ContiniousPrintDemo {
  2.  
  3. public static void main(String[] args) {
  4.  
  5. Counter count = new Counter();
  6.  
  7. Thread t = new Thread(new Runnable(){
  8. @Override
  9. public void run() {
  10. synchronized (count) {
  11. for(int i=0;i<=10;i=i+2){
  12. if(!count.isEven()){
  13. try {
  14. count.wait();
  15. } catch (InterruptedException e) {
  16. // TODO Auto-generated catch block
  17. e.printStackTrace();
  18. }
  19. }
  20. System.out.println(i);
  21. count.setEven(false);
  22. count.notify();
  23. }
  24. }
  25.  
  26. }
  27.  
  28. });
  29.  
  30. Thread t1 = new Thread(new Runnable(){
  31. @Override
  32. public void run() {
  33. synchronized (count) {
  34.  
  35.  
  36. for(int i=1;i<10;i=i+2){
  37. if(count.isEven){
  38. try {
  39. count.wait();
  40. } catch (InterruptedException e) {
  41. // TODO Auto-generated catch block
  42. e.printStackTrace();
  43. }
  44. }
  45. System.out.println(i);
  46. count.setEven(true);
  47. count.notify();
  48. }
  49. }
  50. }
  51. });
  52.  
  53. t.start();
  54. t1.start();
  55.  
  56. }
  57.  
  58. }
  59.  
  60. class Counter{
  61. boolean isEven =true;
  62.  
  63. public boolean isEven() {
  64. return isEven;
  65. }
  66.  
  67. public void setEven(boolean isEven) {
  68. this.isEven = isEven;
  69. }
  70.  
  71. }
Add Comment
Please, Sign In to add comment