The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
October 2001

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

give me solution pleeease

Posted by Chet Underwood, Esq. on October 22, 2001 at 5:30 PM

What do you mean by "it doesn't work"?

By the way, where did you learn this horrible coding style? Clarity in coding can facilitate clarity in thinking and vice versa, you know. This design looks pretty confusing, too; you have this (opaquely-named) class "a" which is itself a Thread should have a method which creates threads that call a method in the original thread? What the heck is going on? Are you actually trying to create a factory method, which should be creating "a" objects, not anonymous thread objects?

In particular, among other things, you are trying to run a method of an object's constructor (whatever that means):


void f(int i )
{
new Thread( new Runnable()
{
public void run()
{
method_1() ;
}
} ).start();
}

If you want to run a method on a new object, you need to do it like this:


(new CheesyObject()).method();

or this:

CheesyObject cheese = new CheesyObject();
cheese.method();

The second method may be better, as you are learning, because it is more clear, readable and less likely to cause mistakes. Also, I hope the variable names you chose were just for posting the example. Finally, you can download Thinking in Java for free and it includes a chapter on threading, with examples that are very similar to what you are trying to do.

By the way, if "method_1()" modifies the "a" object and is not synchronized, when multiple subthreads start calling it, you are in for chaos (so the method should be renamed to "wreakHavok()").

Maybe if you post the actual homework assignment, it would be easier to understand what you are trying to accomplish.

Finally, before I stumble off my soapbox, can you ask your instructor to spend some time discussing the importance of good coding style?

- Chet

> i have the follwoing code :


> class a extends Thread {
> a() { start() ; }
> public void run() {...}
> ....
> void f(int i ) {
> ????
> }
> .....
> void method_1(...) {.....}

> }//class a


> i need method f(int i ) to create new thread when there is any object call it then this new thread will responsible to call method_1(...) which is inside class a

> i try to the follwoing :


> void f(int i ) {
> new Thread(new Runnable(){
> public void run() {
> method_1() ;
> }}).start() ;
> }

> but it doesn't work
> any body help me pleeease
> Nada






Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us