40-Java-Threads

40-Java-Threads - CS107 Spring 2007 Handout 40 May 30, 2007...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
CS107 Handout 40 Spring 2007 May 30, 2007 Java Threads and Concurrency In Java, by default, execution usually proceeds from the main method in a standard linear, sequential fashion with just one thread of execution. However, Java was built from the ground up to be multi-thread-friendly. The language contains facilities that make it is quite easy to start up new threads to execute in parallel. For example, spawning a new thread for each object in order to model the actions of entities that execute and interact simultaneously is a pretty natural combination of the object- oriented and concurrent paradigms. The Thread class The Thread class in the java.lang package encapsulates a thread. The Thread object responds to many messages that allow you to control thread execution, change the scheduling priority, suspend/resume the thread, and more. The methods we are most interested in are: Thread(String threadName) // constructor for a Thread Thread(Runnable runnable) // wraps a thread around class with a run method void start() // spawns thread, calls run method void run() // intended to be overridden by subclasses boolean isAlive() // is the thread started and hasn’t yet exited void sleep(long numMillis) // sleeps current thread for at least millisecs In order to use threads, you create a new Thread subclass and override the run method to include the code you would like the new Thread to execute. (This is precisely what the Creature hierarchy of your MazeRunner assignment needs to do, and in fact the starter code already handles the thread-creation aspects for you.) Here is a simple Thread subclass that is designed to loop, sleeping for a second and then printing out a message about the number of seconds that it has counted so far. It loops until it hits the target number of seconds specified when the Timer was created:
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
2 public class Timer extends Thread { private int target; // number of seconds to count up to
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 01/14/2010 for the course CS 107 taught by Professor Cain,g during the Spring '08 term at Stanford.

Page1 / 4

40-Java-Threads - CS107 Spring 2007 Handout 40 May 30, 2007...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online