Results 1 to 8 of 8
Like Tree3Likes
  • 1 Post By jim829
  • 1 Post By jim829
  • 1 Post By jim829

Thread: Synchronization question

  1. #1
    jjava7 is offline Member
    Join Date
    Apr 2017
    Posts
    6
    Rep Power
    0

    Default Synchronization question

    Hi
    I'm new to java and threads and I have been watching some tutorial videos but they did not answer my question. My question is what if you have a single thread working as the worker thread of your application and then in your main thread you have render method that's supposed to draw everything. My problem is how do I make sure render() is not called same time when the worker thread is running?


    This is how I create the worker thread:

    Java Code:
    		new Thread(new Runnable() {
    			@Override
    			public void run() {
    
    				while(true) {
    
    					try {
    						Thread.sleep(100);
    						// Do stuff
    					} catch (InterruptedException e) {
    
    					}
    				}
    
    
    			}
    		}).start();

    Render method called by the engine:

    Java Code:
    public void render () {
    // Render stuff
    }

    So how do I make sure that when render() is called the worker thread doesn't change anything while rendering?
    Last edited by jjava7; 04-16-2017 at 05:51 PM.

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Synchronization question

    Java Code:
    public class SyncDemo {
    
       public static void main(String[] args) {
          new Thread(()->loop1()).start();
          loop2();
       }
      
       public synchronized static void loop1() {
          for (int j = 1; j <=10; j++) {
             System.out.println(j*100);
             sleep(1);
          }
       }
       public synchronized static void loop2() {
          for (int j = 1; j <=10; j++) {
             System.out.println(j*1000);
             sleep(1);
          }
       }
       
       private static void sleep(int secs) {
          try {
             Thread.sleep(secs*1000);
          } catch (InterruptedException ie ){}
       }
    }
    To see the difference, remove the synchronized keywords from both methods and rerun. You can also used a boolean flag to control when one method is run over another. Note in the example shown, you have no control over which method runs first.

    Regards,
    Jim
    jjava7 likes this.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  3. #3
    jjava7 is offline Member
    Join Date
    Apr 2017
    Posts
    6
    Rep Power
    0

    Default Re: Synchronization question

    Thanks that works.. But I noticed one weird thing, this does not seem to work:

    the SyncMethod is synchronized but the synchronized has no effect in this sample:
    Java Code:
    new Thread(new Runnable() {
        @Override
        public void run() {
     
            while(true) {
     
                try {
                    Thread.sleep(100);
                    obj.SyncMethod(); // Do stuff --- Does not wait here
                } catch (InterruptedException e) {
     
                }
            }
     
     
        }
    }).start();

    what I had to do to get around this issue was use another method like this:

    Java Code:
    new Thread(new Runnable() {
        @Override
        public void run() {
     
            while(true) {
     
                try {
                    Thread.sleep(100);
                     runIt(); // Do stuff
                } catch (InterruptedException e) {
     
                }
            }
     
     
        }
    }).start();
    
    
    synchronized void runIt()
    {
    obj.SyncMethod(); // --- Waits in here like supposed to
    }


    So I guess only member methods in class work with synchronized ?

  4. #4
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: Synchronization question

    Could you make a complete program that compiles, executes and shows the problem. The bits and pieces of code you've posted are complete.

    synchronized has no effect in this sample:
    No it is not using the synchronized method runIt.
    I only see one call to the synchronized method: runIt.
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    jjava7 is offline Member
    Join Date
    Apr 2017
    Posts
    6
    Rep Power
    0

    Default Re: Synchronization question

    Ok I created new project to demonstrate the problem. this is libgdx project in android studio:

    Java Code:
    package com.testinggdx.game;
    
    
    import com.badlogic.gdx.Gdx;
    import com.badlogic.gdx.graphics.GL20;
    
    
    
    public class MyGdxGame extends GdxTest  {
    
    
    
    	class Tester
    	{
    		synchronized void test()
    		{
    			System.out.println("test() begin ");
    			MyGdxGame.sleep(2);
    			System.out.println("test() end");
    		}
    	}
    
    	Tester tester;
    
    	@Override
    	public void create () {
    
    		tester = new Tester();
    
    		new Thread(new Runnable() {
    			public void run() {
    
    				while(true) {
    
    					//tester.test(); // Does not work, does not sleep
    
    					runTester(); // Works
    
    					try {
    						Thread.sleep(100);
    					} catch (InterruptedException e) {
    					}
    				}
    
    
    			}
    		}).start();
    
    	}
    
    	synchronized void runTester()
    	{
    		tester.test();
    	}
    
    
    	private static void sleep(float secs) {
    		try {
    			Thread.sleep((int)(secs*1000));
    		} catch (InterruptedException ie ){}
    	}
    
    
    	@Override
    	public synchronized void render () {
    
    		System.out.println("render() start ");
    
    		MyGdxGame.sleep(0.25f);
    
    
    		Gdx.gl.glClearColor(0.2f, 0.2f, 0.2f, 1);
    		Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    
    
    		System.out.println("render() end ");
    	}
    
    	@Override
    	public void resize (int width, int height) {
    
    	}
    
    	@Override
    	public void dispose () {
    
    	}
    }
    so calling directly tester.test(); does not work (the code doesn't sleep nor lock), but calling runTester(); works.
    Last edited by jjava7; 04-16-2017 at 09:19 PM.

  6. #6
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: Synchronization question

    libgdx project in android studio:
    Ok, that is not much use for Java SE users.

    I guess since you have working code, your questions are answered.
    If you don't understand my response, don't ignore it, ask a question.

  7. #7
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Synchronization question

    Quote Originally Posted by jjava7 View Post
    so calling directly tester.test(); does not work, but calling runTester(); works.
    Synchronized methods only work on the same objects which are running in different threads. In your case above,
    tester and MyGdxGame are two different instances and would not be sync'd. But by putting the tester call in a sync'd method
    inside the MyGdxGame class, you have move the synchronization into the MyGdxGame class. Here is a smaller, example:

    Java Code:
    public class SyncDemo {
       Tester tester;
       public static void main(String[] args) {
        new SyncDemo().begin();
       }
       
       public void begin() {
          tester = new Tester();
          new Thread(()->render()).start();
          tester.runIt();  // later, comment this out and uncomment the next statement and re-run
    //      runTester(); 
       }
       
       public synchronized void runTester() {
          tester.runIt();
       }
       
       public synchronized void render() {
          for (int j = 0; j < 10; j++) {
             System.out.println(j*100);
             try {
             Thread.sleep(1000);
             } catch (InterruptedException ie) {}
          }
       }     
          
    }
    
    class Tester {
       public synchronized void runIt() {
          for (int j = 0; j < 10; j++) {
             System.out.println(j);
             try {
             Thread.sleep(1000);
             } catch (InterruptedException ie) {}
          }
       }     
    }
    Read-up on synchronization and threads in the tutorials in my signature. It may help.

    Regards,
    Jim
    jjava7 likes this.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  8. #8
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Synchronization question

    One more suggestion. Understanding threads at their basic level is important for more advanced java programming (I am still learning more about them). However, before you decide to grow your own solutions, make certain you check out the Java concurrent package. It has many sophisticated classes for doing thread related activities.

    Regards,
    Jim
    jjava7 likes this.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. Help me please with synchronization
    By d3m3tri0 in forum New To Java
    Replies: 9
    Last Post: 10-30-2013, 08:07 PM
  2. Need help with synchronization
    By boblettoj99 in forum Threads and Synchronization
    Replies: 1
    Last Post: 05-08-2012, 03:22 AM
  3. Some Thread Synchronization Question?
    By javakt in forum Threads and Synchronization
    Replies: 3
    Last Post: 06-11-2011, 05:58 PM
  4. synchronization question
    By oguz in forum Threads and Synchronization
    Replies: 2
    Last Post: 07-22-2008, 08:56 AM
  5. Synchronization problems
    By Jack in forum Advanced Java
    Replies: 2
    Last Post: 07-02-2007, 01:17 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •