Threads

Back Up Next

 

Threads
Consult introductory systems text for understanding behind Threads
Basic - threads allow multiple things to happen "simultaneously" in Java
Mutual Exclusivity
synchronized keyword - forces mutual exclusivity on whatever method/object it acts on.
synchronized classes - ensures only one thread can be in the static class method at a time
synchronized methods - ensures only one thread can be in the class method at a time
synchronized objects - obtains lock on specific objects
Inter-Thread communication
wait - the thread waits to be notified (when certain conditions are met)
notify - notify any thread waiting on the object
notifyAll - notify all threads waiting on the object
Thread Management
sleep - give up execution time slice for a fixed amount of time
yield - give any other running thread its slice of execution time
//Dangerous and deprecated
suspend - make a running thread temporarily stop
resume - make a suspended thread running again
stop - permanently stop a thread

PingPong.java

class PingPong extends Thread {
	String word;
	int delay;

	PingPong(String whatToSay, int delayInterval) {
		word = whatToSay;
		delay = delayInterval;
	}
	public void run() {
		try {
			for (;;) {
				System.out.print(word + " ");
				sleep(delay);					//wait for delay ms
			}
		} catch (InterruptedException e) {
			return;								//end on any error
		}
	}

	public static void main(String[] args) {
		new PingPong("ping", 33).start();		//repeat 1/30 sec
			new PingPong("PONG", 100).start();		//repeat 1/10 sec
	}
}