View Single Post
  #1 (permalink)  
Old 11-20-2007, 04:51 PM
blowguy blowguy is offline
Member
 
Join Date: Nov 2007
Posts: 1
blowguy is on a distinguished road
Problem with synhronization.
Hello to all posters.

I am quite new to threads, so I need a little bit of Your help.

From what I understand, keyword synchronized is for defining a part of code(statement or method) that can be executed only by one thread at the same time. Other threads which will be competing for synchronized code must wait till previous thread has completed it.

I have a synchronized method mySwap(), which is actually executed by two threads at the same time(Pavediens1 and Pavediens2). And an error message is displayed in the console.

Code:
class uzd11 { public static int a, b; public static boolean entered; static class myThread extends Thread { myThread() { } synchronized void myswap()//two threads at the same time are executing this method, but i want that if this metdod is executed by one thread, other will wait { //an error message check - we want only one thread to be executing this method if (entered == true) System.out.println("Error: Threads actually are not synchronized");//this error message is always displayed. entered = true;//while we are in this method this flag is true int tmp = a; a = b; b = tmp; entered = false;//exiting method - flag ir false } public void run() { for (int i = 0; i < 1900000; ++i) { myswap();//call synchronized method } } } public static void main(String args[]) { a = 2; b = 3; //two synchronized threads Thread pavediens1 = new myThread(); Thread pavediens2 = new myThread(); pavediens1.start(); pavediens2.start(); try {// lets wait for threads to merge pavediens1.join(); pavediens2.join(); } catch (InterruptedException ignore) {} //Just make sure, that threads have merged... if (pavediens1.isAlive()) System.out.println("Pavediens 1 is Alive"); if (pavediens2.isAlive()) System.out.println("Pavediens 1 is Alive"); //---===--- System.out.println(a); System.out.println(b); } }
CONSOLE: Error: Threads actually are not synchronized

Am I missing the point what is synchronized code? Or is it bug in Java?

Last edited by blowguy : 11-20-2007 at 05:06 PM.
Reply With Quote
Sponsored Links