Runnable和Thread,RunnableThread

作者: 王中王开奖结果计算机  发布:2019-11-02

Runnable和Thread,RunnableThread

1、Runnable是一个接口,当落到实处该接口时须要复用run方法,在run方法中落到实处和谐的逻辑。

2、Thread是一个类,它事实上完结了Runnable方法,也正是说当你通过new 贰个Thread得到贰个线程实例时,其实便是重写runnable里面包车型大巴run方法。当你通过贯彻runnable创造三个线程实例时,你须要将runnable实例传递二个thread,然后通过.start开启线程。

3、Runnable能够线程同步,可是Thread不得以线程同步,比方黄金年代共有10张票,你能够拉开3个线程同期卖票,假如您通过持续thread成立一个卖票的类,实例化3个线程会各自卖10张票,生龙活虎共就卖出了30张,这时候您通过落到实处runnable所创制的卖票类,只需求实例化一个对象,将三个目的传递给八个thread,然后展开八个线程,你会意识多个线程意气风发共只会卖10张。

4、以下是卖票的代码

package com.shine.test;
/**
 * 通过继承thread的卖票类
 * @author ASUS
 *
 */
public class MyThread extends Thread {

    public   int ticks = 10;
    boolean flag = true;
    public MyThread(String string) {
        this.setName(string);
    }

    @Override
    public void run() {
        while(flag){
            saleTick();
        }
    }

    public void saleTick() {
        if(ticks > 0){
            ticks--;

            System.out.println(Thread.currentThread().getName()+":"+ticks);
        }else{
            flag = false;
        }
    }

}

package com.shine.test;
/**
 * 通过实现Runnable的卖票类
 * @author ASUS
 *
 */
public class MyRunnable implements Runnable {

    public  int ticks = 10;
    boolean flag = true;
    @Override
    public void run() {
        while(flag){
            saleTick();
        }

    }
    public void saleTick() {
        if(ticks > 0){
            ticks--;
            System.out.println(Thread.currentThread().getName()+":"+ticks);
        }else{
            flag = false;
        }
    }
}

package com.shine.test;

public class Test {

    /**测试
     * @param args
     */
    public static void main(String[] args) {
        MyThread myThread1 = new MyThread("thread1");
        MyThread myThread2 = new MyThread("thread2");
        MyThread myThread3 = new MyThread("thread3");
        myThread1.start();
        myThread2.start();
        myThread3.start();

        MyRunnable myRunnable = new MyRunnable();
        Thread runnable1 = new Thread(myRunnable);
        Thread runnable2 = new Thread(myRunnable);
        Thread runnable3 = new Thread(myRunnable);
        runnable1.setName("runnable1");
        runnable2.setName("runnable2");
        runnable3.setName("runnable3");
        runnable1.start();
        runnable2.start();
        runnable3.start();

    }

}

结果:
thread1:9
thread1:8
thread1:7
thread1:6
thread1:5
thread1:4
thread1:3
thread1:2
thread1:1
thread1:0
thread2:9
thread2:8
thread2:7
thread2:6
thread2:5
thread2:4
thread2:3
thread2:2
thread2:1
thread2:0
thread3:9
runnable1:9
runnable1:8
runnable1:7
runnable1:6
runnable1:5
runnable1:4
runnable1:3
runnable1:2
runnable1:1
runnable1:0
thread3:8
thread3:7
thread3:6
thread3:5
thread3:4
thread3:3
thread3:2
thread3:1
thread3:0

鉴于系统自个儿的线程选用主题材料 全部由runnable1达成了卖票 但累加只卖出了10张 thread的则卖出了30张

 

1、Runnable是一个接口,当落到实处该接口时索要复用run方法,在run方法中落到实处和睦的逻辑。 2、Thread是一个类,它其实...

本文由王中王开奖结果发布于王中王开奖结果计算机,转载请注明出处:Runnable和Thread,RunnableThread

关键词:

上一篇:没有了
下一篇:没有了