当前位置 主页 > 网站技术 > 代码类 >

    Java并发编程之常用的多线程实现方式分析

    栏目:代码类 时间:2020-02-07 12:12

    本文实例讲述了Java并发编程之常用的多线程实现方式。分享给大家供大家参考,具体如下:

    概述

    常用的多线程实现方式有2种:

    1. 继承Thread类

    2. 实现Runnable接口

    之所以说是常用的,是因为通过还可以通过JUC(java.util.concurrent)包中的线程池来实现多线程。关于线程池的内容,我们以后会详细介绍;现在,先对的Thread和Runnable进行了解。

    Thread简介

    Thread 是一个类。Thread本身就实现了Runnable接口。它的声明如下:

    public class Thread implements Runnable {}
    
    

    Thread的作用是实现多线程。

    ThreadTest.java 源码

    class MyThread extends Thread{ 
     private int ticket=10; 
     public void run(){
      for(int i=0;i<20;i++){ 
       if(this.ticket>0){
        System.out.println(this.getName()+" 卖票:ticket"+this.ticket--);
       }
      }
     } 
    };
    public class ThreadTest { 
     public static void main(String[] args) { 
      // 启动3个线程t1,t2,t3;每个线程各卖10张票!
      MyThread t1=new MyThread();
      MyThread t2=new MyThread();
      MyThread t3=new MyThread();
      t1.start();
      t2.start();
      t3.start();
     } 
    }
    
    

    运行结果

    Thread-0 卖票:ticket10
    Thread-1 卖票:ticket10
    Thread-2 卖票:ticket10
    Thread-1 卖票:ticket9
    Thread-0 卖票:ticket9
    Thread-1 卖票:ticket8
    Thread-2 卖票:ticket9
    Thread-1 卖票:ticket7
    Thread-0 卖票:ticket8
    Thread-1 卖票:ticket6
    Thread-2 卖票:ticket8
    Thread-1 卖票:ticket5
    Thread-0 卖票:ticket7
    Thread-1 卖票:ticket4
    Thread-2 卖票:ticket7
    Thread-1 卖票:ticket3
    Thread-0 卖票:ticket6
    Thread-1 卖票:ticket2
    Thread-2 卖票:ticket6
    Thread-2 卖票:ticket5
    Thread-2 卖票:ticket4
    Thread-1 卖票:ticket1
    Thread-0 卖票:ticket5
    Thread-2 卖票:ticket3
    Thread-0 卖票:ticket4
    Thread-2 卖票:ticket2
    Thread-0 卖票:ticket3
    Thread-2 卖票:ticket1
    Thread-0 卖票:ticket2
    Thread-0 卖票:ticket1

    Runnable简介

    Runnable 是一个函数式接口,该接口中只包含了一个run()方法。它的定义如下:

    @FunctionalInterface
    public interface Runnable {
     public abstract void run();
    }
    
    

    Runnable的作用,实现多线程。我们可以定义一个类A实现Runnable接口;然后,通过new Thread(new A())等方式新建线程。

    RunnableTest.java 源码

    class MyThread implements Runnable{ 
     private int ticket=10; 
     public void run(){
      for(int i=0;i<20;i++){ 
       if(this.ticket>0){
        System.out.println(Thread.currentThread().getName()+" 卖票:ticket"+this.ticket--);
       }
      }
     } 
    }; 
    public class RunnableTest { 
     public static void main(String[] args) { 
      MyThread mt=new MyThread();
      // 启动3个线程t1,t2,t3(它们共用一个Runnable对象),这3个线程一共卖10张票!
      Thread t1=new Thread(mt);
      Thread t2=new Thread(mt);
      Thread t3=new Thread(mt);
      t1.start();
      t2.start();
      t3.start();
     } 
    }
    
    

    运行结果

    Thread-0 卖票:ticket10
    Thread-2 卖票:ticket8
    Thread-1 卖票:ticket9