Runnable和Thread的异同

2019-03-04  本文已影响0人  咖A喱
创建线程
第一种方式:继承Thread类
  1. 定义类继承Thread

  2. 复写Thread类中的run方法

  3. 调用线程的start方法,

    该方法有两个作用:启动线程、调用run方法

package model.three_week;
class Demo extends Thread{
    public void run(){
        for (int i = 0; i <60 ; i++) {
            System.out.println("Run:"+i);
        }
    }
}

public class MultuThreadingDemo1 {
    public static void main(String[] args) {
        Demo demo =new Demo();
        demo.start();
        for (int i = 0; i <60 ; i++) {
            System.out.println("Main:"+i);
        }
    }
}
第二种方式:实现Runnable接口
  1. 步骤:

    1. 定义类实现Runnable接口

    2. 覆盖Runnable接口中的run方法

      将线程要运行的代码存放在该run方法中

    3. 通过Thread类建立线程对象

    4. 将Runnable接口的子类对象作为实际参数传递给Thread类的构造函数

      为什么要将Runnable接口的子类对象传递给Thread的构造函数?

      因为,自定义的run方法所属的对象是Runnable接口的子类对象,所以要让线程去指定指定对象的run方法,就必须明确run方法所属对象

    5. 调用Thread类的start方法开启线程并调用Runnable接口的子类的run方法

package model.three_week;

import com.sun.org.apache.xerces.internal.parsers.CachingParserPool;

import java.util.concurrent.SynchronousQueue;

//需求:四个窗口同时卖100张票
//如果用继承类方法,将会必须使用static变量,或者导致线程创建不使用的无意义
//安全问题:多线程会出现卖错票的情况,如(0、-1、-2)
public class RunnableDemo {
    public static void main(String[] args) {

/*        Tickect1 tickect1_1 = new Tickect1();
        Tickect1 tickect1_2 = new Tickect1();
        Tickect1 tickect1_3 = new Tickect1();
        Tickect1 tickect1_4 = new Tickect1();
        tickect1_1.start();
        tickect1_2.start();
        tickect1_3.start();
        tickect1_4.start();*/
        Tickect2 tickect2 = new Tickect2();
        Thread thread1 = new Thread(tickect2);
        Thread thread2 = new Thread(tickect2);
        Thread thread3 = new Thread(tickect2);
        Thread thread4 = new Thread(tickect2);
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
    }
}

class Tickect1 extends Thread {
    //    private static int tick = 100;
    private int tick = 100;
    Object object = new Object();

    public void run() {
/*        for (int i = tick; i > 0; i--) {
            System.out.println(currentThread().getName() + "sale----" + i);
            tick--;
        }*/
        while (true) {
            show();
        }
    }

    public synchronized void show() {
        if (tick > 0) {
            try {
                Thread.sleep(10);
            } catch (Exception e) {
                System.out.println(e);
            }//模拟运行机处理多个进程的过程
            System.out.println(currentThread().getName() + "sale----" + tick--);
        }

    }
}

class Tickect2 implements Runnable {
    private int tick = 100;

    public void run() {
        while (true) {
            if (tick > 0) {
                System.out.println(Thread.currentThread().getName() + "sale----" + tick--);
            }
        }
    }
}



实现方式和继承方式有什么区别
上一篇 下一篇

猜你喜欢

热点阅读