zoukankan      html  css  js  c++  java
  • java 多线程基础

    1.创建新线程

      ①继承自Thread

      将类声明为java.lang.Thread的子类并重写run方法

    public class MyThread extends Thread {
    
        @Override
        public void run() {
            //线程体的执行方法
            //线程体
            for(int i = 0;i<50;i++) {
                System.out.println("~~子线程:"+ i);
            }
        }
    
    }

      启动线程,不是调用MyThread.run()函数,而是调用start()函数:

    MyThread myThread = new MyThread();
    //myThread.run();    
    //启动线程
    myThread.start();

      ②实现Runnable

      定义实现java.lang.Runnable接口的类,Runnable接口中只有一个方法public void run(),用来定义线程运行体:

    public class MyRunnable implements Runnable {
        //实现了Runnable就必须实现run方法,在run方法中执行线程体
    
        @Override
        public void run(){
            for(int i = 0;i<50;i++ ) {
                System.out.println("runnable子线程:"+ i);
            }
        }
    }

      启动线程时,需要创建Thread实例时将这个类的实例作为参数传递到线程实例内部。然后再启劢:

    Thread thread = new Thread(new MyRunnable());
    thread.start();

    实例:使用多线程模拟铁路售票系统,实现5个售票点发售某日某次列车的1000张车票,一个售票点用一个线程表示。

    package com.cmq.test;
    /**
    *@author chenmeiqi
    *@version 2020年2月13日 上午9:59:44
    */
    public class MainTest {
    
        public  static void main(String[] args) {
            
            
            //第二种线程启动方式
            Thread thread1 = new Thread(new MyRunnable());
            thread1.setName("售票点1");
            Thread thread2 = new Thread(new MyRunnable());
            thread2.setName("售票点2");
            Thread thread3 = new Thread(new MyRunnable());
            thread3.setName("售票点3");
            Thread thread4 = new Thread(new MyRunnable());
            thread4.setName("售票点4");
            Thread thread5 = new Thread(new MyRunnable());
            thread5.setName("售票点5");
            thread1.start();
            thread2.start();
            thread3.start();
            thread4.start();
            thread5.start();
            
            
    //        
        }
    
    }
    package com.cmq.test;
    /**
    *@author chenmeiqi
    *@version 2020年2月13日 上午10:11:38
    *Tunnable 线程实现售票问题
    */
    public class MyRunnable implements Runnable {
        //实现了Runnable就必须实现run方法,在run方法中执行线程体
        private static int ticket = 300;
        @Override
        public void run() {
            //线程体的执行方法
            //线程体
            while(this.ticket>0) {
                System.out.println(Thread.currentThread().getName() + ":" + this.ticket--);
            }
            
        }
    }

    注:类属性ticket加static是为了防止数据冲突。

  • 相关阅读:
    解决:微信小程序富文本识别不了空白p标签的方法
    微信小程序
    fastadmin
    微信小程序
    fastadmin使用笔记
    fastadmin使用笔记
    您有新的订单,请注意查收 提示音
    js获取视频第一帧生成图片
    解决JQ WeUI 的 Picker无法动态传值的问题
    微擎 人人商城小程序获取不到用户信息
  • 原文地址:https://www.cnblogs.com/qilin20/p/12302631.html
Copyright © 2011-2022 走看看