二、启用多线程
1)通过Runnable接口创建线程
a.定义一个“任务类”并是实现Runnable接口,覆写Runnable接口run()方法 【run()方法中定义具体的任务代码或处理逻辑】;
b.定义“任务类”后,创建“任务类”对象;
c.任务必须在线程中执行,创建Thread类对象,将实现Runnable接口的任务类作为参数传递给Thread类对象;
d.调用Thread类对象的start()方法,启动一个线程【run()方法执行,结束则线程终止】。
package com.muzeet.mutithread;
2
3 //每个任务都是Runable接口的一个实例,任务是可运行对象,线程是便于任务执行的对象。必须创建任务类,重写run方法定义任务
4 public class ThreadDemo1 implements Runnable {
5 private int countDown = 10;
6 @Override
7 //重写run方法,定义任务
8 public void run() {
9 while(countDown-- >0)
10 {
11 System.out.println("$" + Thread.currentThread().getName()
12 + "(" + countDown + ")");
13 }
14 }
15 //调用start方法会启动一个线程,导致任务中的run方法被调用,run方法执行完毕则线程终止
16
17 public static void main(String[] args) {
18 Runnable demo1 = new ThreadDemo1();
19
20 Thread thread1 = new Thread(demo1);
21 Thread thread2 = new Thread(demo1);
22 thread1.start();
23 thread2.start();
24
25 System.out.println("火箭发射倒计时:");
26
27
28 }
29
30 }
2)继承Thread类创建线程
a.创建一个“任务类”继承Thread类【Thread类实现了Runnable接口】,并重写run()方法;
b.创建“任务类”对象;
c.调用start()方法。
package com.muzeet.mutithread;
2
3 //每个任务都是Runable接口的一个实例,任务是可运行对象,线程即可运行对象。必须创建任务类,重写run方法定义任务
4 public class ExtendFromThread extends Thread {
5 private int countDown = 10;
6 @Override
7 //重写run方法,定义任务
8 public void run() {
9 while(countDown-- >0)
10 {
11 System.out.println("$" + this.getName()
12 + "(" + countDown + ")");
13 }
14 }
15 //调用start方法会启动一个线程,导致任务中的run方法被调用,run方法执行完毕则线程终止
16
17 public static void main(String[] args) {
18
19 ExtendFromThread thread1 = new ExtendFromThread();
20 ExtendFromThread thread2 = new ExtendFromThread();
21 thread1.start();
22 thread2.start();
23
24 System.out.println("火箭发射倒计时:");
25
26
27 }
28
29 }
复制代码