Wednesday, August 20, 2014

Two threads in a synchronized block at the same time .

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.hello;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author gagandsi
 */
public class Hello {
    
    
    public   synchronized void method( String s){
        if (s.equals("1")){
            try {
                System.out.println("this : " + this + " : "+ s);
                Thread.currentThread().yield();
                this.wait(1000);
                System.out.println("This is " + s + " again");
            } catch (InterruptedException ex) {
                Logger.getLogger(Hello.class.getName()).log(Level.SEVERE, null, ex);
            }
        }else {
            System.out.println("This is  " + s);
        }
    }
    

    public static void main(String[] args) {
        try {
            Hello one = new Hello();
            Thread t = new Thread(){

                @Override
                public void run() {
                    super.run(); 
                    one.method("1");
                }
            
        } ;
            
            Thread t2 = new Thread(){

                @Override
                public void run() {
                    super.run(); 
                    one.method("2");
                }
            
        } ;
            t.start();
            t2.start();
        } finally {
        }

    }
}

2 comments:

Anonymous said...

It can be done using the simple wait call as well. I dont know why you use yield.

Noms said...

Please post your sample with wait . I doubt it will work.