Java 线程很简单就三种状态:就绪,运行,空闲 (进程是分配资源的基本单位,线程在进程中运行)
Java要运行线程,这个类要么是继承Thread,要么Runnable。(我们一般选择接口,因为Java是单继承模式)
Java的线程是有优先级的。//高级 分的时间片多 反之亦然
两个实例
Thread继承:
- // 通过继承 Thread 创建线程
- class NewThread extends Thread {
- NewThread() {
- // 创建第二个新线程
- super("Demo Thread");
- System.out.println("Child thread: " + this);
- start(); // 开始线程
- }
- // 第二个线程入口
- public void run() {
- try {
- for(int i = 5; i > 0; i--) {
- System.out.println("Child Thread: " + i);
- // 让线程休眠一会
- Thread.sleep(50);
- }
- } catch (InterruptedException e) {
- System.out.println("Child interrupted.");
- }
- System.out.println("Exiting child thread.");
- }
- }
- public class ExtendThread {
- public static void main(String args[]) {
- new NewThread(); // 创建一个新线程
- try {
- for(int i = 5; i > 0; i--) {
- System.out.println("Main Thread: " + i);
- Thread.sleep(100);
- }
- } catch (InterruptedException e) {
- System.out.println("Main thread interrupted.");
- }
- System.out.println("Main thread exiting.");
- }
- }
复制代码 Runnable 接口:
- // 创建一个新的线程
- class NewThread implements Runnable {
- Thread t;
- NewThread() {
- // 创建第二个新线程
- t = new Thread(this, "Demo Thread");
- System.out.println("Child thread: " + t);
- t.start(); // 开始线程
- }
- // 第二个线程入口
- public void run() {
- try {
- for(int i = 5; i > 0; i--) {
- System.out.println("Child Thread: " + i);
- // 暂停线程
- Thread.sleep(50);
- }
- } catch (InterruptedException e) {
- System.out.println("Child interrupted.");
- }
- System.out.println("Exiting child thread.");
- }
- }
- public class ThreadDemo {
- public static void main(String args[]) {
- new NewThread(); // 创建一个新线程
- try {
- for(int i = 5; i > 0; i--) {
- System.out.println("Main Thread: " + i);
- Thread.sleep(100);
- }
- } catch (InterruptedException e) {
- System.out.println("Main thread interrupted.");
- }
- System.out.println("Main thread exiting.");
- }
- }
复制代码
|
|