Android Thread Runnable

不问归期 提交于 2019-11-30 02:08:11

Runnable就是一个接口

public interface Runnable {      
/**
     * Starts executing the active part of the class' code. This method is
     * called when a thread is started that has been created with a class which
     * implements {@code Runnable}.
     */      
    void run();
}

Thread是线程,继承了Runnable接口,同时init方法可以传入Runnable,作为Target

public Thread(Runnable target, String name) {
        init(null, target, name, 0);
    }
    
private void init(ThreadGroup g, Runnable target, String name, long stackSize) {
        Thread parent = currentThread();
        if (g == null) {
            g = parent.getThreadGroup();
        }

        g.addUnstarted();
        this.group = g;

        this.target = target;
        this.priority = parent.getPriority();
        this.daemon = parent.isDaemon();
        setName(name);

        init2(parent);

        /* Stash the specified stack size in case the VM cares */
        this.stackSize = stackSize;
        tid = nextThreadID();
    }

 @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

通过传入Runnable,可以实现多线程共享资源

public class TicketThread extends Thread{
 
    private int ticket = 10;
 
    public void run(){
        for(int i =0;i<10;i++){
            synchronized (this){
                if(this.ticket>0){
                    try {
                        Thread.sleep(100);
                        System.out.println(Thread.currentThread().getName()+"卖票---->"+(this.ticket--));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
 
    public static void main(String[] arg){
        TicketThread t1 = new TicketThread();
        new Thread(t1,"线程1").start();
        new Thread(t1,"线程2").start();
    }
}
 输出:
线程1卖票—->10
线程1卖票—->9
线程1卖票—->8
线程2卖票—->7
线程2卖票—->6
线程1卖票—->5
线程1卖票—->4
线程2卖票—->3
线程2卖票—->2
线程1卖票—->1

Runnable实现

public class TicketRunnable implements Runnable{
 
    private int ticket = 10;
 
    @Override
    public void run() {
        for(int i =0;i<10;i++){
            //添加同步快
            synchronized (this){
                if(this.ticket>0){
                    try {
                        //通过睡眠线程来模拟出最后一张票的抢票场景
                        Thread.sleep(100);
                        System.out.println(Thread.currentThread().getName()+"卖票---->"+(this.ticket--));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
 
    public static void main(String[] arg){
        TicketRunnable t1 = new TicketRunnable();
        new Thread(t1, "线程1").start();
        new Thread(t1, "线程2").start();
    }
}
 输出:
线程1卖票—->10
线程1卖票—->9
线程1卖票—->8
线程1卖票—->7
线程2卖票—->6
线程2卖票—->5
线程2卖票—->4
线程2卖票—->3
线程2卖票—->2
线程2卖票—->1

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!