multithreading - Java Thread inter process communication working in boolean variable condition but not in int? -
i have code communicating 2 threads in jre6. when run following program expected output come like,
a: hi
b: hi
a: how r u?
b: im fine wat u?
a: i'm fine
b: me too
class chat { boolean flag = false; public synchronized void gettalk1(string msg) throws interruptedexception { if (flag) { wait(); } system.out.println(msg); flag = true; notify(); } public synchronized void gettalk2(string msg) throws interruptedexception { if (!flag) { wait(); } system.out.println(msg); flag = false; notify(); } } class thread1 extends thread { chat chat; public thread1(chat chat) { this.chat = chat; } string[] talk = { "hi", "how r u?", "i'm fine" }; @override public void run() { (int = 0; < talk.length; i++) { try { chat.gettalk1("a: " + talk[i]); } catch (interruptedexception e) { e.printstacktrace(); } } } } class thread2 extends thread { chat chat; public thread2(chat chat) { this.chat = chat; } string[] talk = { "hi", "im fine wat u?", "me too" }; @override public void run() { (int = 0; < talk.length; i++) { try { chat.gettalk2("b: " + talk[i]); } catch (interruptedexception e) { e.printstacktrace(); } } } } public class conversation { public static void main(string[] args) { chat chat = new chat(); new thread1(chat).start(); new thread2(chat).start(); } }
but when change chat class flag variable boolean int type
class chat { volatile int flag = 2; public synchronized void gettalk1(string msg) throws interruptedexception { if (flag == 1) { wait(); } system.out.println(msg); flag = 2; notify(); } public synchronized void gettalk2(string msg) throws interruptedexception { if (flag == 2) { wait(); } system.out.println(msg); flag = 1; notify(); } }
the output varied , executing not stop
a: hi
a: how r u?
a: i'm fine
...still running
what reason?
compare
if (flag) { wait(); } system.out.println(msg); flag = true; notify();
with
if (flag == 1) { wait(); } system.out.println(msg); flag = 2; notify();
in first case, wait
if flag == true
, set flag = true
. in second case, wait
if flag == 1
, set flag = 2
. logic inverted.
Comments
Post a Comment