Android Thread Runnable

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
发布了230 篇原创文章 · 获赞 24 · 访问量 109万+

猜你喜欢

转载自blog.csdn.net/linzhiji/article/details/100997604