• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

Problem with Chapter 9 Question 1

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all

I tried compiling and running this question and answer in my Java environment but got a different answer to the answers in the book. The question was on Threads i.e.

public class Messager implements Runnable {

public Messager(String name) { this.name = name;}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new Thread(new Messager("Wallace")).start();
new Thread(new Messager("Gromit")).start();


}
private String name;

private synchronized void message(int n) {
System.out.println("\n name - " + name + " " + n);

}

public void run() {
message(1);
//System.out.println("\n One Thread called" );
message(2);
}


}


The answer I got was

Wallace - 1
Wallace - 2


Gromit - 1
Gromit - 2

The answer in the book was

Wallace - 1
Gromit - 1

Gromit - 2
Wallace -2

Can anyone assist or had the same problem too?

Bola
 
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Bola

The question asks which of the given results is possible - only one of the given options can happen. Other results can happen as you've seen.

There's nothing to guarantee in what order the Threads will start and run - over the next pages the book will explain about synchronization and how you can't predict the scheduling for a Thread.

The order in which the names will come out is unpredictable - but you will never see

Gromit-2
Gromit-1

because within a Thread the execution is predictable.

Hope that helps

Paul
reply
    Bookmark Topic Watch Topic
  • New Topic