Thread(or a subclass) and send it the
start()message. (A program can send the
start()message to any object that implements the
Runnableinterface.) The definition of each thread's behavior is contained in its
run()method. A run method is equivalent to
main()in a traditional program: a thread will continue running until
run()returns, at which point the thread dies.
Under the preemptive threading model, the OS interrupts threads at any time, usually after allowing them to run for a period of time (known as a time-slice). As a result, no thread can ever unfairly hog the processor. However, interrupting threads at any time poses problems for the program developer. Using our office example, consider what would happen if a worker preempts another worker making copies halfway through her copy job: the new worker would start his copy job on a machine that already has originals on the glass or copies in the output tray. The preemptive threading model requires that threads use shared resources appropriately, while the cooperative model requires threads to share execution time. Because the JVM specification does not mandate a particular threading model, Java developers must write programs for both models. We'll see how to design programs for either model after looking a bit at threads and communication among threads.