JavaThreads
//Give the thread some code to run! Extend the Thread class, override its run() hook method,
//and call start() on an instance of the extended Thread class
public class MyThread extends Thread {
Public void run() {
//code to run goes here
}
}
//Create a new thread
MyThread myThread = new MyThread();
myThread.start();
***
//2nd "give it some code to run!
//Implement the Runnable interface, override its run() hook method,
//pass the Runnable object to the constructor of a new Thread object,
//and call start() on the Thread object
//Implement the Runnable interface and override its run hook method
public interface Runnable {
public void run(); }
public class MyRunnable implements Runnable {
public void run() {
//code to run goes here
}
}
//create new instance
MyRunnable myRunnable = new MyRunnable();
new Thread(myRunnable).start();
***
//Extending the thread class
public static class PlayPingPongThread extends Thread {
}
***
//Example of two threads being creating to run concurrently
Thread producer = new Thread(new Runnable(){
public void run(){
for(int i = 0; i < mMaxIterations; i++)
buggyQueue.put(Integer.toString(i));
}});
Thread consumer = new Thread(new Runnable(){
public void run(){
for(int i = 0; i < mMaxIterations; i++)
System.out.println(buggyQueue.take());
}});
***
//Stopping a thread
void processBlocking(String input) (
...
while (true) (
try (
Thread. currentThread.sleep (interval) :
synchroniz.d(this) (
while (sceConditionFalse)
wait ();
catch (InterruptedException e)
***
//Using a stop flag to stop a thread.
public class MyRunnable implements Runnable {
private volatile boolean isStopped = false;
public void stopMe() {
isStopped = true;
}
public void run() {
while(isStopped !0 true) {
// a long running operation
}
}