01.Java 多线程 - 实例
来源:互联网 发布:linux stat 文件夹 编辑:程序博客网 时间:2024/06/08 00:54
基本概念
在 Java 中,实现多线程常见的两种方式是:Thread 和 Runnable。
实例探究
1.Runnable
- 定义:它是一个接口,定义了一个名为 run 的抽象方法。源码如下:
public interface Runnable { public abstract void run();}
- 实现方式:实现接口,调用 Thread 的 start 方法启动线程。
class MyRunnable implements Runnable { public void run() { //dosomthing... }}public class Test { public static void main(String[] args) { MyRunnable mr = new MyRunnable(); //将 Runnable 装进 Thread Thread t1 = new Thread(mr); Thread t2 = new Thread(mr); //启动线程 t1.start(); t2.start(); }}
2.Thread
- 定义:Thread 类本身实现了 Runnable 的接口
public class Thread implements Runnable
- 实现方式:实现类,利用 start 方法启动线程。
class MyThread extends Thread { public void run() { //dosomthing... }}public class Test { public static void main(String[] args) { MyThread t1 = new MyThread(); MyThread t2 = new MyThread(); t1.start(); t2.start(); }}
资源共享
使用 Runnable 实现线程,由于多个线程都是基于某一个 Runnable 对象建立的,它们会共享 Runnable 对象上的资源。而 Thread 却不会。
根本原因在于 Thread 中运行的是不同的 Runnable 对象。而 Runnable 实现的线程,从始至终只有一份 Runnable 对象。
1.Thread 实现
观察输出结果,每个线程都卖出了 3 张票,说明对于 ticket 来说,它们是各自独自拥有的,而不是共享的。
class MyThread extends Thread { private int ticket = 3; public void run() { while (this.ticket > 0) { //也可以用 this.getName() 代替,表示换取当前线程名称 System.out.println(Thread.currentThread().getName() + " 卖票:" + this.ticket--); } }}public class Test { public static void main(String[] args) { MyThread t1 = new MyThread(); MyThread t2 = new MyThread(); MyThread t3 = new MyThread(); t1.start(); t2.start(); t3.start(); }}// 输出结果:// Thread-0 卖票:3// Thread-0 卖票:2// Thread-0 卖票:1// Thread-1 卖票:3// Thread-1 卖票:2// Thread-1 卖票:1// Thread-2 卖票:3// Thread-2 卖票:2// Thread-2 卖票:1// Thread-0 卖票:3// Thread-1 卖票:3// Thread-1 卖票:2// Thread-1 卖票:1// Thread-0 卖票:2// Thread-0 卖票:1// Thread-2 卖票:3// Thread-2 卖票:2// Thread-2 卖票:1
2.Runnable 实现
观察输出结果,发现 3 个线程总共就卖了 3张票,与 ticket 的值一样,说明对于它们来说 ticket 是共享的资源。
class MyRunnable implements Runnable { private int ticket = 3; public void run() { while (ticket > 0) { System.out.println(Thread.currentThread().getName() + " 卖票:" + ticket--); } }}public class Test { public static void main(String[] args) { MyRunnable mr = new MyRunnable(); Thread t1 = new Thread(mr); Thread t2 = new Thread(mr); Thread t3 = new Thread(mr); t1.start(); t2.start(); t3.start(); }}// 输出结果:// Thread-0 卖票:3// Thread-2 卖票:1// Thread-1 卖票:2
0 0
- 01.Java 多线程 - 实例
- 【多线程】应用Java多线程实例
- java多线程经典实例
- java多线程经典实例
- java 多线程 实例浅析
- java中的多线程实例
- java多线程爬虫实例
- java多线程实例
- Java多线程实例
- Java多线程实例<转>
- java多线程实现实例
- java 多线程实例二
- java多线程池实例
- java多线程爬虫实例
- Java多线程死锁实例
- java多线程实例
- java多线程实例
- java多线程实例
- 第4章网络层
- 编外话20160606
- leetcode-Partition List-86
- TensorFlow的安装
- AR/VR learning (1)--artoolkit在android studio 上的配置
- 01.Java 多线程 - 实例
- "围观"设计模式(18)--行为型之模板方法模式(TemplateMethod Pattern)
- mySql存储过程中用到的时间函数
- hiho第五周--数字三角形
- Poco c++学习资料
- 数据结构—连通图的遍历—DFS和BFS
- leetcode 99 Recover Binary Search Tree (python)
- 设置状态栏透明
- viewPager