To start a Java thread, we need a java.lang.Runnable
.
Thread thrNew = new Thread(aRunnable);
thrNew.start();
public class Dialog implements Runnable {
@Override
public void run() {
Thread thrCur = Thread.currentThread();
String name = thrCur.getName();
System.out.printf("%s entering Dialog#run\n", name);
while (! Thread.interrupted()) {
System.out.printf("%s looping in Dialog#run\n", name);
}
System.out.printf("%s leaving Dialog#run", name);
}
}
Then we just have to call thread.interrupt()
from the main
.
Once a thread is interrupted, we have to create a new one, we can't start it again. A workaround for this is to make a thread reusable:
public class Dialog { // no longer a Runnable
Thread thread;
Runnable runnable = new Runnable() {
@Override
public void run() {
Thread thrCur = Thread.currentThread();
String name = thrCur.getName();
System.out.printf("%s entering Dialog#run\n", name);
while (!Thread.interrupted()) {
System.out.printf("%s looping in Dialog#run\n", name);
}
System.out.printf("%s leaving Dialog#run", name);
thread = null;
}
};
public boolean start() {
if (thread == null) {
thread = new Thread(runnable);
thread.start();
return true;
}
return false;
}
public void stop() {
if (thread != null)
thread.interrupt();
}
}
To avoid concurrency, we can use the synchronized
keyword:
public class Fifo {
protected Object[] v;
protected int size;
public Fifo() {
v = new Object[100];
size = 0;
}
public void append(Object o) {
synchronized (this) {
v[size] = o;
size++;
} }
public Object get() {
synchronized (this) {
if (size == 0)
return null;
Object o = v[0];
size--;
for (int i = 0; i < size; i++)
v[i] = v[i + 1];
v[size] = null;
return o;
}
}
}
Status:: #wiki/notes/mature
Plantations:: Java
References:: ILOG