JAVA学习笔记(三十八)- 创建实现Runnable接口的线程

来源:互联网 发布:简单特效制作软件 编辑:程序博客网 时间:2024/04/27 17:37

创建实现Runnable接口的线程

/* * 创建线程方式二:实现Runnable接口 * 步骤: * 1.创建一个Runnable接口的实现类 * 2.实现run方法 * 3.创建一个实现类的实例 * 4.创建Thread实例,将实现类的实例作为参数传入 * 5.调用start方法,启动线程并运行run方法 */class MyDemo implements Runnable{    @Override    public void run() {        for (int i = 1; i <= 50; i++) {            System.out.println(Thread.currentThread().getName()+"*****run*******" + i);        }    }}public class Test03 {    public static void main(String[] args) {        //创建Runnable接口实现类的实例        MyDemo d=new MyDemo();        //创建线程,将实现类的实例传入        Thread t=new Thread(d,"MyThread");        //启动线程并执行run方法        t.start();        Thread thread=Thread.currentThread();//获取当前线程实例        for (int i = 1; i <= 50; i++) {            System.out.println(thread.getName()+"*****Hello World*******" + i);        }    }}

多线程

/* * 多线程 *  * 现象:输出结果可能未按顺序依次输出 * 原因:虽然执行了输出的代码,但可能结果暂未打印出来,而此时另一个线程却提前打印了 */public class Test04 {    public static void main(String[] args) {        /*MyThread1 t1 = new MyThread1();        MyThread1 t2 = new MyThread1();        t1.start();        t2.start();*/        MyThread2 mt=new MyThread2();        Thread t1=new Thread(mt, "窗口1");        Thread t2=new Thread(mt, "窗口2");        t1.start();        t2.start();    }}class MyThread1 extends Thread {    // 一般不使用static来操作,原因:1.static在类加载时初始化 2.生命周期太长    static int num = 50;// 票数    @Override    public void run() {        while (num > 0) {            System.out.println(Thread.currentThread().getName() + "******"                    + num--);        }    }}class MyThread2 implements Runnable {    int num = 5000;    @Override    public void run() {        while (num > 0) {            System.out.println(Thread.currentThread().getName() + "******"                    + num--);        }    }}
0 0