java多线程实现方法和比较
来源:互联网 发布:中国资讯型数据库作用 编辑:程序博客网 时间:2024/06/07 00:03
在java中要想实现多线程,有两种手段,一种是继续Thread类,另外一种是实现Runable接口。
对于直接继承Thread的类来说,代码大致框架是:
/** * @author Rollen-Holt 继承Thread类 * */class hello extends Thread { public hello() { } public hello(String name) { this.name = name; } public void run() { for (int i = 0; i < 5; i++) { System.out.println(name + "运行 " + i); } } public static void main(String[] args) { hello h1=new hello("A"); hello h2=new hello("B"); h1.start(); h2.start(); } private String name;}实现Runnable接口:
/** * @author Rollen-Holt 实现Runnable接口 * */class hello implements Runnable { public hello() { } public hello(String name) { this.name = name; } public void run() { for (int i = 0; i < 5; i++) { System.out.println(name + "运行 " + i); } } public static void main(String[] args) { hello h1=new hello("线程A"); Thread demo= new Thread(h1); hello h2=new hello("线程B"); Thread demo1=new Thread(h2); demo.start(); demo1.start(); } private String name;}
那么:为什么我们不能直接调用run()方法呢?
我的理解是:线程的运行需要本地操作系统的支持。
如果你查看start的源代码的时候,会发现:public synchronized void start() { /** * This method is not invoked for the main method thread or "system" * group threads created/set up by the VM. Any new functionality added * to this method in the future may have to also be added to the VM. * * A zero status value corresponds to state "NEW". */ if (threadStatus != 0 || this != me) throw new IllegalThreadStateException(); group.add(this); start0(); if (stopBeforeStart) { stop0(throwableFromStop); }}private native void start0();
实现Runnable接口比继承Thread类所具有的优势:
1):适合多个相同的程序代码的线程去处理同一个资源
2):可以避免java中的单继承的限制
3):增加程序的健壮性,代码可以被多个线程共享,代码和数据独立。
0 0
- java多线程实现方法和比较
- java多线程的实现和比较
- java实现多线程的两种方法的比较
- java实现多线程两种方法的比较
- Java 多线程实现方法
- java 创建多线程两种方法比较
- Java中Thread和Runnable方法实现多线程差异性分析
- Java 中多线程的实现方法之Thread和Runnable
- Java多线程简介和两种实现方法
- Java 多线程实现方法和switch的理解
- java【多线程】两个实现多线程的方法
- java实现多线程有两种方法
- java实现多线程有两种方法
- java多线程的实现方法
- java多线程--实现runnable方法
- java多线程的实现方法
- Java实现多线程的方法
- Java实现多线程的方法
- iPhone鼎力支持 H.265编码技术及画质PK
- Qt Visual Studio插件 安装失败
- 安全狗IIS6.0解析webshell访问限制bypass
- BZOJ2938【AC自动机】
- 杭电1715 大菲波数
- java多线程实现方法和比较
- 动态内存管理
- Fn和CTRL的故事
- package和import
- OpenCV2.4.4中调用SIFT特征检测器进行图像匹配
- 多个视图结果显示于一个共用预览视图内
- Google protocol buffer(4)—Google protocol buffer + socket实现message的连续传输
- jackson (json、xml的序列化与反序列化)
- PHP连接mysql数据库出现连接失败的解决方法