Creating Threads


To reiterate... threads can be created in one of two ways. Extend Thread or implement Runnable. Just to clarify, since Thread is extended, that means it's a class. As well, since Runnable is implemented, that would mean it's an interface. Just to be clear.

There are no hard and fast rules on which one is better, only opinion. Therefore each developer should employ thier own stratagy. I generally use the logger startagy although your mileage may vary.

CREATED 2013-01-08 13:12:31.0

00-19-4E

UPDATED 2013-01-08 13:12:55.0

Extending The Thread Class...


To extend Thread, the run() method must be overriden or else the class won't do anything because Threads run method doesn't do anything...

 package com.your.package.name; public class MyThread extends Thread{  public MyThread(){}  @Override <-- you must override the run method  public void run(){  // code that executes when the Thread is running.  } } 

Since Thread was extended, all of the Thread functionality comes with it. Therefore, all you need to do is start it. That would be something like this:

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

CREATED 2013-01-07 13:10:18.0

00-19-40

UPDATED 2013-01-08 15:10:18.0

Implementing The Runnable Interface...


If for some reason Threadcan not be extended, there is the Runnable interface. Implementing Runnable is pretty simple as the interface has a single method... run(). Implementing Runnable would be something like this

 package com.your.package.name; public class MyClass implements Runnable{  public MyClass(){}  public void run(){ <-- you must implement the run method  // code that executes when the Thread is running.  } } 

Running a class that implements runnable is slightly different that starting a class that extends thread. Essentially, the new class is instantiated and passed to the Thread class in it's contructor...

 public static class main(String[] args){  MyClass newThread = new MyClass(); <-- Instantiate the class that implements Runnable...  Thread t = new Thread(newThread); <-- Pass the class to Thread...  t.start(); <-- Start the Thread  } 																

And that's all there is to starting a thread! This is not the hard part... managing threads is!

CREATED 2013-01-07 14:31:17.0

00-19-41

UPDATED 2013-01-08 15:13:14.0


CREATED 2013-01-08 14:52:41.0

00-19-53

UPDATED 2013-01-08 14:52:41.0

L
I
N
K
S

DBID: db.wam

Page Server: Ruger

©2019 Leistware.com
        Hello anonymous