Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6936487
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T12:14:25+00:00 2026-05-27T12:14:25+00:00

So I have the following code: import java.lang.Thread; import java.lang.Integer; class MyThread extends Thread

  • 0

So I have the following code:

import java.lang.Thread;
import java.lang.Integer;

class MyThread extends Thread {
private int id;

MyThread(int i){
    id = i;
    }

public void run() {
    while(true){
        try{                    
            synchronized(Global.lock){
                Global.lock.wait();
                if(Global.n == 0) {System.out.println(id); Global.lock.notify(); break;}
                --Global.n;
                System.out.println("I am thread " + id + "\tn is now " + Global.n);
                Global.lock.notify();
                }
            }
        catch(Exception e){break;}
        }
    }
}

class Global{
public static int n;
public static Object lock = new Object();
}

public class Sync2{
public static final void main(String[] sArgs){
    int threadNum = Integer.parseInt(sArgs[0]);
    Global.n = Integer.parseInt(sArgs[1]);

    MyThread[] threads = new MyThread[threadNum];

    for(int i = 0; i < threadNum; ++i){
        threads[i] = new MyThread(i);
        threads[i].start();     
        }
    synchronized(Global.lock){Global.lock.notify();}
}
}

two parameters are entered: a number n and the number of threads to be created. Every thread decreases n by one and then passes control. All threads should stop when n is 0. It seems to work fine so far, but the only problem is that in most of the cases all threads except one terminate. And one is hanging on. Any idea why?

And yes, this is part of a homework, and that is what I’ve done so far (I was no provided with the code). I’am also explicitly restricted to use a synchronized block and only wait() and .notify() methods by the task.

EDIT: modified the synchronized block a bit:

synchronized(Global.lock){
  Global.lock.notify();
  if (Global.n == 0) {break;}
  if (Global.next != id) {Global.lock.wait();  continue;}
  --Global.n;
  System.out.println("I am thread " + id + "\tn is now " + Global.n);
  Global.next = ++Global.next % Global.threadNum;
  }

now threads act strictly in the order they are created. Its pretty unclear from the task wording, but might be the right thing.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T12:14:25+00:00Added an answer on May 27, 2026 at 12:14 pm

    You have a race condition. Think about what happens with a single worker thread. Global.n is set to 1 and then the thread starts. It immediately goes into a wait state. Suppose, though, that notify() had already been called on the main thread. Since the worker thread hasn’t yet entered a wait state, it isn’t notified. Then, when it finally does call wait(), there are no other threads around to call notify(), it stays in the wait state forever. You need to fix up your logic to avoid this race condition.

    Also, do you really want a single worker thread to decrement Global.n more than once? That can easily happen with your while (true) ... loop.

    EDIT
    You also have another logic problem with a single thread. Suppose it enters the wait state and then the notify() in main is called. It wakes the worker thread which decrements Global.n to 0, calls notify(), and then goes back to waiting. The problem is that notify() didn’t wake any other thread because there were no other threads to wake. So the one worker thread will wait forever. I haven’t analyzed it fully, but something like this might also happen with more than one worker thread.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following code: import java.util.*; public class SellTransaction extends Transaction { private
Say I have the following code: import java.lang.InterruptedException; import javax.swing.SwingWorker; public class Test {
I have the following simple Java code: package testj; import java.util.*; public class Query<T>
I have the following code: import com.apple.dnssd.*; public interface IServiceAnnouncer { public void registerService();
I have the following code: Imports MySql.Data.MySqlClient Imports MySql.Data.Types Public Class FormMain Private Sub
I have the following code: import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.ScrollPaneConstants; public
import java.io.*; public class Demo{ public static void main(String[] args){ File f = new
I have the following simple code: package test; import javax.swing.*; class KeyEventDemo { static
I have the following code import smtplib from email.mime.text import MIMEText smtpserver = 'smtp.gmail.com'
I have the following code: import string import random d =[random.choice(string.uppercase) for x in

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.