Java实现Runnable接口方式实现多线程的优势

1.继承Thread

package com.test.thread;

public class TicketThread1 extends Thread {
    private int ticket = 5;

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            if (ticket > 0) {
                System.out.println("Thread剩余==" + ticket--);
                ;
            }
        }
    }
}

2.实现Runnable

package com.test.thread;

public class TicketThread2 implements Runnable {
    private int ticket = 5;

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            if (ticket > 0) {
                System.out.println("Runnable剩余==" + ticket--);
                ;
            }
        }

    }
}

3.测试Test

package com.test.thread;

public class TicketTest {
    public static void main(String[] args) {
        TicketThread1 ticket1 = new TicketThread1();
        TicketThread1 ticket2 = new TicketThread1();
        TicketThread1 ticket3 = new TicketThread1();
        ticket1.start();
        ticket2.start();
        ticket3.start();

        TicketThread2 ticketRunnable = new TicketThread2();
        new Thread(ticketRunnable).start();
        new Thread(ticketRunnable).start();
        new Thread(ticketRunnable).start();

    }
}

4.输出结果:

Thread剩余==5
Thread剩余==5
Thread剩余==5
Thread剩余==4
Thread剩余==4
Thread剩余==3
Thread剩余==4
Thread剩余==2
Thread剩余==3
Thread剩余==1
Thread剩余==3
Thread剩余==2
Thread剩余==1
Thread剩余==2
Runnable剩余==5
Thread剩余==1
Runnable剩余==4
Runnable剩余==1
Runnable剩余==3
Runnable剩余==2

结论:从程序运行结果可发现,继承Thread实际上是3个线程分别卖了5张票
而实现Runnable3个线程共同卖了5张票

总结:实现Runnable接口比继承Thread的优势有:
①适合多个相同的程序代码的线程去处理统一资源的情况
②可以避免由于java单继承特征带来的局限性
③增强开发程序的健壮性,代码可以多个线程共享,代码和数据是独立的

所以开发首选实现Runnable接口方式来实现多线程操作!

你可能感兴趣的:(Java)