Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java Language
Expertise: Beginner
Mar 20, 1997

Why Does Spawned Thread Work on PC and not Sun?

Question:
This may be too vague, but:

I spawn a thread (after a button click) which brings up a new window. This works great on my PC running Netscape 3.0 and Internet Explorer, but it doesn't work on a Sun (Netscape 3.0). I've also tried it on another PC running Internet Explorer and it didn't work there, either.

Any clues?

Answer:
I'm guessing the parent thread goes on to do other work, while the window created by the child thread never appears. If that's true, the problem is probably a selfish parent.

There are two styles of multithreading: cooperative and preemptive. In cooperative multithreading, a thread controls the CPU until it voluntarily gives it up, usually by performing I/O or by explicitly giving it up with a call to sleep() or wait(). A thread that never relinquishes control of the CPU is called a selfish thread.

In preemptive multithreading, the OS periodically interrupts (preempts) the thread controlling the CPU, places it at the end of the queue of runnable threads, and gives the next runnable thread control of the CPU. This technique is also called time slicing. The multi- threading facilities on Solaris and Windows 3.1 are cooperative, while the facilities on Windows NT and Windows 95 are preemptive.

Since Java accomplishes multithreading by using the multithreading facilities of the host OS, one can observe system dependent behavior in a multithreaded application.

Here's a selfish parent thread:

class Parent extends Thread {

      public void run() {
         Child c = new Child();
         c.start();
         for(;;);
      }
   } 
Immediately after spawning a child, c, the parent enters a tight infinite loop, never voluntarily releasing the CPU.

Assume the child merely displays a string:

   class Child
extends Thread {

      public void run() {
         System.out.println("Hello World");
      }
   } 
On Solaris or Windows 3.1, we'll never see the child's pitiful output. On Windows NT and Windows 95, we do see the child's message because the OS will periodically preempt the selfish parent to give the child a chance at the CPU.

We can turn the selfish parent into a cooperative parent by having it periodically release the CPU for a few milliseconds using the sleep() or wait() methods:

   class Parent extends Thread {

      public void run() {
         Child c = new Child();
         c.start();
         for(;;) {
           try {sleep(5);}  // sleep for 5 milliseconds
           catch(InterruptedException e) {System.exit(1);}
         }
      }
   }
 
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap