01.Java 多线程 - 实例

来源:互联网 发布:linux stat 文件夹 编辑:程序博客网 时间:2024/06/08 00:54

基本概念

在 Java 中,实现多线程常见的两种方式是:Thread 和 Runnable。


实例探究

1.Runnable

  • 定义:它是一个接口,定义了一个名为 run 的抽象方法。源码如下:
public interface Runnable {    public abstract void run();}
  • 实现方式:实现接口,调用 Threadstart 方法启动线程。
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