Independent Threads
An Introduction with Examples in Java |
Prof. David Bernstein
|
Computer Science Department |
bernstdh@jmu.edu |
Indexer
createIndex()
to
return quicklyIndexer
public class SlasherDriver
{
public static void main(String[] args)
{
Slasher plus, slash;
1 slash = new Slasher();
6 slash.setCount(3);
8 slash.start();
10 plus = new Slasher("+");
14 plus.setCount(2);
16 plus.start();
}
}
public class Slasher implements Runnable
{
private int count;
private String symbol;
private Thread controlThread;
public Slasher()
{
2 this("/");
}
public Slasher(String symbol)
{
3 11 this.symbol = symbol;
4 12 count = 0;
5 13 controlThread = new Thread(this);
}
public void run()
{
A C E G for (int i=0; i<count; i++) a c e
{
B D F System.out.print(symbol); b d
}
}
public void setCount(int count)
{
7 15 this.count = count;
}
public void start()
{
9 17 controlThread.start();
}
}
this
reference must not be allowed to
"escape" during constructionThread
object's start()
method in a constructor (because the Thread
object's
constructor is passed this
)Thread
can be
changed using its setDaemon()
method