继承于Thread类
- 创建一个继承与Thread类的子类
- 重写Thread类的run() 方法 ,将想要用子线程执行的操作写在 run() 方法中
- 在主线程中创建继承Thread类的子类的对象
- 调用对象的 start() 方法启动子线程 (注意 这里使用的是 start() 方法 【底层是start0方法】 而不是 run() 方法)
package Thread_;
public class Exercise_3 {
public static void main(String[] args) {
Cat cat = new Cat();
cat.start();
}
}
class Cat extends Thread{
int times = 0;
@Override
public void run() {
while (true){
System.out.println("喵喵" + (++times) + "线程名" +Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (times == 10){
break;
}
}
}
}
Thread.currentThread().getName():获取当前线程名称
sleep(long millitime) :当前线程睡眠,指定时间当前线程阻塞
实现Runnable接口
- 创建一个实现类Runnable接口的类
- 实现类去实现Runnable中的抽象方法:run( )
- 创建实现类的对象
- 将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
- 通过Thread类的对象调用start( )
package Thread_;
public class Exercise_2 {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new T2());
for (int i = 0; i < 10; i++) {
System.out.println("hi"+i);
if (i == 5){
thread.start();
thread.join();
}
Thread.sleep(1000);
}
System.out.println(thread.isAlive());
}
}
class T2 implements Runnable{
private int count = 0;
@Override
public void run() {
while (true) {
System.out.println("hello"+(++count));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (count == 10){
break;
}
}
}
}
开发中优先选择实现Runnable接口方式,因为实现的方式没有类的单继承性的局限性,而且实现的方式更适合处理多个线程有共享数据的情况。
join():在线程a中调用线程b的join(),此时线程a进入阻塞状态,直到线程b完全执行完以后,线程a才结束阻塞转态
isAlive():判断当前线程是否存活
-
实现Callable接口
package Thread_;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class Exercise_4 {
public static void main(String[] args) {
numThread numthread= new numThread();
FutureTask futureTask = new FutureTask(numthread);
new Thread(futureTask).start();
}
}
//创建实现Callable接口的实现类
class numThread implements Callable {
//实现call方法,将此线程操作放在call中
@Override
public Object call() throws Exception {
int sum =0;
for (int i = 0; i <= 100;i ++) {
if(i%2==0) {
System.out.println(i);
sum += i;
}
}
return sum;
}
}
Callable接口功能更强大,支持泛型,call()可以有返回值,可以抛异常