代码改变世界

java 多线程基础

2020-02-13 12:05  默默不语  阅读(131)  评论(0编辑  收藏  举报

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是为了防止数据冲突。