您的位置:首页 > 编程语言 > Java开发

【Java基础】——线程Thread VS Runnable

2017-10-13 00:00 357 查看

进程和线程的关系

多个线程构成一个进程,线程是进程中的一个元素,例如QQ.exe查看电脑进程的时候发现只有一个进程,但是我们可以同时和多个用户聊天交流,而且可以一边聊天,刷空间之类。对每一个用户的聊天就是一个线程,多个用户的互动构成进程。

演示一个不使用多线程的Demo,也就是单线程

public class SingleDemo{ public static void main(String[] args){ MyThread myThread = new MyThread(); myThread.run(); while(true){ System.out.println("Main方法在运行"); } } } class MyThread{ public void run(){ while (true){ System.out.println("MyThread类的run()方法在运行"); } } }

根据demo可以知道mian中的run方法永远都不可能被执行



一张图说明何为单线程和多线程!



从图中很清晰表明我们使用多线程的原因

继承Thread创建多线程

public class DemoThread{ public static void main(String[] args){ MyThread myThread = new MyThread(); myThread.start(); while(true){ System.out.println("run()方法在运行"); } } } class MyThread extends Thread { public void run(){ while(true){ System.out.println("MyThread类的run()方法在运行"); } } }

显示结果



实现Runnable接口创建多线程

public class DemoRunnable{ public static void main(String[] args){ RunnableDemo runnable = new RunnableDemo(); Thread mythread = new Thread(runnable); mythread.start(); while(true){ System.out.println("main类的run()方法在运行"); } } } class RunnableDemo implements Runnable{ public void run(){ while(true){ System.out.println("RunnableDemo类的run()方法在运行"); } } }

显示结果



Runnable的实现机制

其实是利用Thread(Runnable target)这个构造函数实现的,Runnable是一个接口其中只有一个run()方法,在调用Thread时,其实实现的是接口Runnable中的方法。

Thread VS Runnable两者的不同

先说一个例子,火车站售票会牵扯到一个资源共享的问题,资源就是车票,每个售票都相当与一个线程,假如有100张票,每张票理论上都只能买一个人,下面看Thread和Runnable的处理方式

继承Thread

public class DemoExceple{ public static void main(String[] args){ new TicketWindow().start(); new TicketWindow().start(); new TicketWindow().start(); new TicketWindow().start(); } } class TicketWindow extends Thread{ private int tickets = 100; public void run(){ while(true){ if(tickets>0){ Thread th = Thread.currentThread(); String name = th.getName(); System.out.println(name+"正在发售第"+tickets--+"张票"); } } } }

运行结果



根据这个运行结果,发现每一张票都被重复卖了四次,明显这种多线程的方式并不太适合资源共享的问题。

实现Runnable接口

public class RunnableDemoTest{ public static void main(String[] args){ TicketWindow tw = new TicketWindow(); new Thread(tw,"窗口1").start(); new Thread(tw,"窗口2").start(); new Thread(tw,"窗口3").start(); new Thread(tw,"窗口4").start(); } } class TicketWindow implements Runnable{ private int tickets = 100; public void run(){ while(true){ if(tickets>0){ Thread th = Thread.currentThread(); String th_name = th.getName(); System.out.println(th_name+"正在发售第"+tickets--+"张票"); } } } }

运行结果



根据运行结果发现使用Runnable接口刚好能解决我们资源共享的问题。

结论

根据上述两种情况的对比,发现Runnable接口相对Thread更实用一些。

1、Runnable适合多个相同的代码线程去处理同一个资源的情况,把线程同程序代码做了很好的隔离,更接近面向对象的思想,解决资源共享的问题。

2、Runnable可以避免Java中单继承的局限性,一个子类继承父类,不能在继承Thread实现多线程,Runnable接口刚好是完美的解决方案。

整体上来说,大部分应用程序会采用Runnable的方式来创建多线程。

小编也是刚刚开始学习,如有错误之处还请指出,不胜感激!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: