2、第二种创建线程的方式
package cn.itcast_05; /* * 方式2:实现Runnable接口 * 步骤: * A:自定义类MyRunnable实现Runnable接口 * B:重写run()方法 * C:创建MyRunnable类的对象 * D:创建Thread类的对象,并把C步骤的对象作为构造参数传递 */ public class MyRunnableDemo { public static void main(String[] args) { // 创建MyRunnable类的对象 MyRunnable my = new MyRunnable(); // 创建Thread类的对象,并把C步骤的对象作为构造参数传递 // Thread(Runnable target) // Thread t1 = new Thread(my); // Thread t2 = new Thread(my); // t1.setName("林青霞"); // t2.setName("刘意"); // Thread(Runnable target, String name) Thread t1 = new Thread(my, "林青霞"); Thread t2 = new Thread(my, "刘意"); t1.start(); t2.start(); } }
package cn.itcast_05; public class MyRunnable implements Runnable { @Override public void run() { for (int x = 0; x < 100; x++) { // 由于实现接口的方式就不能直接使用Thread类的方法了,但是可以间接的使用 System.out.println(Thread.currentThread().getName() + ":" + x); } } }
重点:多线程第一种创建方式与第二种的区别
有了方式1,为什么还来一个方式2呢?
A:可以避免由于java单继承带来的局限性
B:适合多个相同程序的代码去处理同一个资源的情况,把线程同程序的代码,数据有效分离,较好的体现了面向对象的设计思想
重点:多线程的生命周期
A:新建
B:就绪
C:运行
D;阻塞
E:死亡
java-day09-Thread-第二种方式多线程以及两者对比
最新推荐文章于 2023-03-31 08:50:58 发布