[Multi-threading] Will this code cause problem? (run & main exist in the same class)

H

Haitao

Hi all,

I just saw a code fragment written by someone as follows:

public class MyThread extends Thread
{
public void run()
{
... (do something)
}

public static void main(String[] args)
{
Thread t= new MyThread ();
t.start();
... (do something)
}
}

I am new to Java multi-threading program, and haven't seen such a coding
style. Will putting run() and main() in the same class and executing this
class cause some unexpected problems?

Thanks!
 
A

Andreas Leitgeb

Haitao said:
I just saw a code fragment written by someone as follows:
public class MyThread extends Thread
{
public void run() { ... (do something) }
public static void main(String[] args)
{
Thread t= new MyThread (); t.start(); ... (do something)
}
}
I am new to Java multi-threading program, and haven't seen such a coding
style. Will putting run() and main() in the same class and executing this
class cause some unexpected problems?

No. main and run can peacefully co-exist :)

What types of problems did you fear? The only potential for
unexpected problems lies in the "... (do something)"-parts :)
 
A

Arne Vajhøj

Haitao said:
I just saw a code fragment written by someone as follows:

public class MyThread extends Thread
{
public void run()
{
... (do something)
}

public static void main(String[] args)
{
Thread t= new MyThread ();
t.start();
... (do something)
}
}

I am new to Java multi-threading program, and haven't seen such a coding
style. Will putting run() and main() in the same class and executing this
class cause some unexpected problems?

Not necessarily.

Impossible to tell based on the available information.

It depends on whether run and main access something in
a thread unsafe manner or not.

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top