• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Multithreading

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
can there be start() inside run(){.......} in thread . It seems to be meaning less, since run() can be invoked by Thread.start().
i mean to say without t(thread instance).start() if i create only instance. Then i will call start() in run(), then will it run.
public void run() {
start();//anywhere
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}

}
 
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Ayaz uddin wrote:can there be start() inside run(){.......}



There has to be. Every single bit of Java code we write is executed inside the run() method of some thread. If we couldn't call start() inside run(), we couldn't call start() at all.

It seems to be meaning less, since run() can be invoked by Thread.start().



start() and run() do two completely different things.

start() causes the JVM to create a new thread of execution, parallel to, concurrent with, and independent of the current thread and any other threads.

run() is called by start() to execute that task that we created our Runnable for.

i mean to say without t(thread instance).start() if i create only instance. Then i will call start() in run(), then will it run.
public void run() {
start()



No. Bad.

1. Don't call this.start() on a Thread object inside its run() method. You'll probably get an exception if you do. By the time run() gets called, start() has already been called.

2. You should not extend Thread in the first place, so this won't even be an issue. It can't come up. You should implement Runnable instead. You're not creating a specialized kind of Thread. You're just creating a task to be executed in its own thread.
 
reply
    Bookmark Topic Watch Topic
  • New Topic