package unit07; publicclassHelloThreadextendsThread{ publicvoidrun(){ System.out.println("Hello from a thread!"); } publicstaticvoidmain(String args[]){ (new HelloThread()).start(); } }
创建线程的关系跟运行进程的顺序没有关系
1 2 3 4 5 6 7 8 9
package unit07; publicclassHelloRunnableimplementsRunnable{ publicvoidrun(){ System.out.println("Hello from a thread!"); } publicstaticvoidmain(String args[]){ (new Thread(new HelloRunnable())).start(); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
java.lang.Thread +Thread(tagert: Runnable)// Creates a new thread to run the target object +run(): void/** Invoked by the Java runtime system to execute the thread. You must override this method and provide the code you want your thread to execute in your thread class. This method is never directly invoked by the runnable object in a program, although it is an instance method of a runnable object.*/ +start(): void//Starts the thread that causes the run() method to be invoked by the JVM. +interrupt(): void//Interrupts this thread. If the thread is blocked, it is ready to run again. +isAlive(): boolean//Tests whether the thread is currently running +setPriority(p: int): void//Sets priority p (ranging from 1 to 10) for this thread. +join(): void//Waits for this thread to finish. +sleep(millis: long): void//Puts the runnable object to sleep for a specified time in milliseconds. 静态数 +yield(): void//Causes this thread to temporarily pause and allow other threads to execute./ +isInterrupted(): Boolean //Tests whether the current thread has been interrupted. +currentThread(): Thread //Returns a reference to the currently executing thread object.
线程池示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; publicclassExecutorDemo{ publicstaticvoidmain(String[] args){ // Create a fixed thread pool with maximum three threads ExecutorService executor = Executors.newFixedThreadPool(3); // Submit runnable tasks to the executor executor.execute(new PrintChar('a', 100)); executor.execute(new PrintChar('b', 100)); executor.execute(new PrintNum(100)); // Shut down the executor executor.shutdown(); } }