你最愿意做的哪件事,才是你的天赋所在

0%

java-多线程

创建线程的两种方式

1
2
3
4
5
6
7
8
9
package unit07;
public class HelloThread extends Thread {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new HelloThread()).start();
}
}

创建线程的关系跟运行进程的顺序没有关系

1
2
3
4
5
6
7
8
9
package unit07;
public class HelloRunnable implements Runnable {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(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;
public class ExecutorDemo {
public static void main(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();
}
}
-------------你最愿意做的哪件事才是你的天赋所在-------------