3.多线程之Thread VS Runnable
来源:互联网 发布:什么事非农数据 编辑:程序博客网 时间:2024/05/20 16:34
两种方式的比较
Runnable方式可以避免Thread方式由于Java单继承特性带来的缺陷。
Runnable可以被多个线程(Thread实例)共享,适用于多个线程处理统一资源资源
分别使用Runnable和Thread模拟火车站卖票
使用Thread方式
/** * 一个共五张火车票,三个窗口卖 * /class MyThread extends Thread { private int count = 5; private String name; @Override public void run() { while (count > 0) { count--; System.out.println(name + "卖出一张票还剩" + count + "张"); } } MyThread(String name) { this.name = name; }}public class ThreadTicket { public static void main(String[] args) { MyThread myThread1 = new MyThread("窗口1"); MyThread myThread2 = new MyThread("窗口2"); MyThread myThread3 = new MyThread("窗口3"); myThread1.start(); myThread2.start(); myThread3.start(); }}
样例输出:
窗口1卖出一张票还剩4张
窗口1卖出一张票还剩3张
窗口1卖出一张票还剩2张
窗口1卖出一张票还剩1张
窗口3卖出一张票还剩4张
窗口3卖出一张票还剩3张
窗口3卖出一张票还剩2张
窗口2卖出一张票还剩4张
窗口2卖出一张票还剩3张
窗口2卖出一张票还剩2张
窗口2卖出一张票还剩1张
窗口2卖出一张票还剩0张
窗口3卖出一张票还剩1张
窗口1卖出一张票还剩0张
窗口3卖出一张票还剩0张
使用Runnable方式
/** * 一个共五张火车票,三个窗口卖 * /class MyRunnable implements Runnable { private int count = 5; @Override public void run() { while (count > 0) { count--; System.out.println(Thread.currentThread().getName() + "卖出一张票还剩" + count + "张"); } }}public class RunnableTicket { public static void main(String[] args) { MyRunnable myRunnable = new MyRunnable(); Thread myThread1 = new Thread(myRunnable, "窗口1"); Thread myThread2 = new Thread(myRunnable, "窗口2"); Thread myThread3 = new Thread(myRunnable, "窗口3"); myThread1.start(); myThread2.start(); myThread3.start(); }}
样例输出
窗口3卖出一张票还剩2张
窗口3卖出一张票还剩1张
窗口3卖出一张票还剩0张
窗口2卖出一张票还剩2张
窗口1卖出一张票还剩2张
大家体会一下吧
使用Thread方式时,new三个Thread对象,每个对象都有自己count,使用Runnable方式时,由于时通过同一个Runnable实现类对象new三个Thread对象,他们共用一个count。
阅读全文
0 0
- 3.多线程之Thread VS Runnable
- 多线程之Thread VS Runnable
- Java多线程之 Thread VS Runnable
- JAVA多线程之Thread VS Runnable
- 细说多线程之Thread VS Runnable
- 细说多线程之Thread VS Runnable
- 多线程 Thread VS Runnable
- 多线程 Thread VS Runnable
- 【java0006】多线程 - Thread VS Runnable
- 多线程编程(三)--创建线程之Thread VS Runnable
- 多线程编程(三)--创建线程之Thread VS Runnable
- Java多线程之 Thread VS Runnable 【带案例】
- Java 多线程之 Runnable VS Thread 及其资源共享问题
- 多线程编程(三)--创建线程之Thread VS Runnable
- JAVA多线程之Thread&&Runnable
- JAVA多线程Thread VS Runnable详解
- Java多线程Thread VS Runnable详解
- Java多线程之Thread VS Runnable(根据慕课网视频编写)
- SSM框架Web程序的流程(Spring SpringMVC Mybatis)
- [UVA] 10881
- 二叉树的后序遍历非递归算法
- SpringMVC之请求处理源码分析从service到doDispatch之doDispatch分析(二)
- 学习akka之dispatcher
- 3.多线程之Thread VS Runnable
- git(十三)-git裸库与submodule
- 第八章 SpringMVC引入css-跟赵大笨笨学SpringMVC
- POJ 3050:Hopscotch
- 数据传参
- spring boot整合mybatis
- 为什么实践高于研究
- osgi入门(一)
- 学习akka之邮箱