Win a copy of Zero to AI - A non-technical, hype-free guide to prospering in the AI era this week in the Artificial Intelligence and Machine Learning forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Paul Clapham
  • Bear Bibeault
  • Jeanne Boyarsky
  • Ron McLeod
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Jj Roberts
  • Stephan van Hulst
  • Carey Brown
  • salvin francis
  • Scott Selikoff
  • fred rosenberger

Thread question

Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Imagine a piece of code written like this:
public static void go(long time) throws InterruptedException{
synchronized(new String("sync")){
if(time>0){ //line1
Thread.sleep(time); // line2


Now imagine that these code is called by 2 threads - Thread1 has the time variable set to 5000 and Thread2 has the variable time set to 1000. If Thread1 is started first (and assume runs first) and it reaches line1 BUT DOES not yet reach line2, but Thread2 has already reached line2 - because the method is static => the first thread (Thread1) might be sleeping for 1 second instead of the 5 seconds desired. I am correct (hope I was clear about the issue that I am facing)? Thank you very much.

Ranch Hand
Posts: 317
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Eugene,

sorry, but I don't understand your question. Why should Thread 1 (which called the method long with parameter long = 5000) sleep only 1000ms? It will sleep 5000ms and gets back to the runnable state.
And as a reminder: Your synchronized block is of no use, because every time a thread enters this bloc a new instance of String is created. So no thread will be blocked here.

If you have a bad day in October, have a slice of banana cream pie. And this tiny ad:
the value of filler advertising in 2020
    Bookmark Topic Watch Topic
  • New Topic