có thể có mã phân bổ đặc biệt, trong khi những người khác (chẳng hạn như các thiết bị I / O) có thể yêu cầu nhiều hơn nói chung và mã phát hành. Ví dụ, trong việc xác định cách tốt nhất để sử dụng CPU, hệ điều hành có thói quen lập lịch trình CPU-có tính đến tốc độ của CPU, công việc phải được thực hiện, | Thread Libraries 135 inciude include DWORD Sum data is shared by the thread s the thread runs in this separate function DWORD WINAPI Summation LPVOID Param DWORD Upper DWORD Param for DWORD i 0 i Upper i Sim i return 0 int main int argc char argv DWORD Threadld HANDLE ThreadHandle int Param perform some basic error checking if argc 1 2 fprintf stderr An integer parameter is required n return Param atoi argv l if Param 0 fprintf stderr An integer 0 is required n return - 1 create the thread ThreadHandle CreateThread NULL default security attributes 0 default stack size Summation thread function Param parameter to thread function 0 default creation flags SThreadld returns the thread identifier if ThreadHandle 1 NULL now wait for the thread to finish WaitForSingleObj ect ThreadHandle INFINITE close the thread handle CloseHandle ThreadHandle printff sum d n Sum Figure Multithreaded c program using the Win32 API. 136 Chapter 4 Threads f of confrol even a simple Java program consisting of only a mainO method runs as a single thread in the JVM There are two techniques for creating threads in a Java program. One approach is to create a new class that is derived from the Thread class and to override its nm method. An alternative and more commonly used technique is to define a class that implements the Runnable interface. The Runnable interface is defined as folloWs public interface Runnable . t public abstract void run When a class implements Runnable it must define a runO method. The code implementing the run method is what runs as a separate thread. Figure shows the Java version of a multithreaded program that determines the summation of a non-negative integer. The Summation class implements the Runnable interface. Thread creation is performed by creating an object instance of the Thread class and passing the constructor a Runnable object. Creating a Thread object does not specifically create the new thread rather it is the method that .