创建线程的两种方式:
继承Thread类:(一个多线程分别完成自己的任务)
编写简单,可直接做线程
适用于单继承
实现Runnable接口:(一个多线程共同完成一个任务)
避免单继承局限性
便于共享资源
通过代码感受为何说Runnable接口便于共享资源(模拟现实生活中的抢票过程)
如果用继承Thread类:
* @Description//创建线程模拟抢票过程
*/
public class MyThread1 extends Thread {
private int ticket=10;
public void run(){
for (int i = 0; i <= 10; i++) {
if (this.ticket>0){
System.out.println(Thread.currentThread().getName()+"买票--"+this.ticket--);
}
}
}
public static void main(String[] args) {
MyThread1 t1=new MyThread1();
t1.setName("窗口1");
MyThread1 t2=new MyThread1();
t2.setName("窗口2");
t1.start();
t2.start();
}
}

我们可以看到,定义了票数一共十张,而代码却是两个窗口卖出了20张票,显然不符合我们的要求。
如果用Runnable接口:
* @Description//创建线程模拟抢票过程
*/
public class MyThread1 implements Runnable {
private int ticket = 10;
public void run() {
for (int i = 0; i <= 10; i++) {
if (this.ticket > 0) {
System.out.println(Thread.currentThread().getName() + "买票--" + this.ticket--);
}
}
}
public static void main(String[] args) {
Runnable runnable = new MyThread1();
Thread t1 = new Thread(runnable, "窗口1");
Thread t2 = new Thread(runnable, "窗口2");
t1.start();
t2.start();
}
}

我们可以看到用Runnable接口创建线程,可以达到我们的目的
747

被折叠的 条评论
为什么被折叠?



