本节摘要:介绍创建线程的两种基本方式Thread,Runnable,并比较两者的区别和联系,最后通过实例进行演示
一、Thread 和 Runnable异同点
相同点 | 区别 |
---|---|
可以实现多线程 | 1. Thread是类,Runnable是接口 2. 线程可以驱动任务(java编程思想),那么Thread是线程,Runnable是任务 3. Runnable可以实现资源共享 |
二、实现多线程的方式
2.1 Runnable:Runnable只包含一个接口,它实际上是一个函数式接口,可以通过实现Runnable接口来描述一种任务
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
实现多线程的方式为以下两步:
(1) class MyRunnable implements Runnable{}
(2) Thread t = new Thread(new MyRunnable()); t.start();
2.2 Thread:Thread实现了Runnable接口,它本身是一个类
public class Thread implements Runnable {}
实现多线程的方式为:
(1)class MyThread extends Thread{}
(2)Thread t = new MyThread(); t.start();
对于"Runnable是任务"这句话的理解:
查看Thread类的源码,发现Thread 的run()方法如下:
@Override
public void run() {
if (target != null) {
target.run();
}
}
这里的target实际就是Runnable对象,通过Thread的构造函数传进来的
三、示例:我们以售卖mix2为例演示Thread 和Runnable的用法,假设本次只能售卖10台mix2
public class MyRunnable implements Runnable {
private int num = 10;
public static void main(String[] args) {
Runnable runnable = new MyRunnable();
//runnable 可以实现资源共享,下面3个线程共享一个runnable,一共卖了10部Mix2
Thread t1 = new Thread(runnable);
Thread t2 = new Thread(runnable);
Thread t3 = new Thread(runnable);
t1.start();
t2.start();
t3.start();
}
@Override
public void run() {
for (int i = 0; i < 50; i++) {
synchronized (this) {
//2个线程
if (this.num > 0) {
System.out.println(Thread.currentThread().getName() + ",num:" + num--);
}
}
Thread.yield();
}
}
}
输出内容如下(输出会有不同):
Thread-0,num:10
Thread-1,num:9
Thread-1,num:8
Thread-1,num:7
Thread-1,num:6
Thread-1,num:5
Thread-1,num:4
Thread-1,num:3
Thread-1,num:2
Thread-1,num:1
可以看到,我们启动3个线程,共享一个runnable实例,一共只卖出10部mix2
下面以Thread为例:
public class ThreadExample extends Thread {
private int num = 10;
public static void main(String[] args) {
ThreadExample t1 = new ThreadExample();
ThreadExample t2 = new ThreadExample();
ThreadExample t3 = new ThreadExample();
t1.start();
t2.start();
t3.start();
}
public void run() {
for (int i = 0; i < 20; i++) {
if (num > 0) {
System.out.println(Thread.currentThread().getName()+"---"+num--);
}
}
}
}
输出结果:
Thread-0---10
Thread-0---9
Thread-0---8
Thread-0---7
Thread-0---6
Thread-0---5
Thread-0---4
Thread-0---3
Thread-0---2
Thread-0---1
Thread-1---10
Thread-1---9
Thread-1---8
Thread-1---7
Thread-1---6
Thread-1---5
Thread-1---4
Thread-1---3
Thread-1---2
Thread-1---1
Thread-2---10
Thread-2---9
Thread-2---8
Thread-2---7
Thread-2---6
Thread-2---5
Thread-2---4
Thread-2---3
Thread-2---2
Thread-2---1
可以看到,每个线程都卖出10部mix2,这不符合我们的预期
四、总结
继承Thread和实现Runnable接口都可以实现多线程,Runnable可以实现资源共享
转载请注明作者及出处,并附上链接http://www.jianshu.com/u/ada8c4ee308b