程序员

线程

2019-01-11  本文已影响15人  我可能是个假开发

线程

一、线程的概述

1.进程与线程

注意:电脑上的程序同时在运行。“多任务”操作系统能同时运行多个进程(程序),实际是由于CPU分时机制的作用,使每个进程都能循环获得自己的CPU时间片。但由于轮换速度非常快,使得所有程序好象是在“同时”运行一样。

线程负责了代码的执行,运行任何一个java程序,jvm在运行的时候都会创建一个main线程执行main方法中所有代码。

一个java应用程序至少有几个线程?
至少有两个线程, 一个是主线程负责main方法代码的执行,一个是垃圾回收器线程,负责了回收垃圾。

2.多线程的好处与弊端

多线程的好处:

多线程的弊端:

二、多线程的创建方式

1.方式一:继承Thread类

步骤:
①自定义一个类继承Thread类。
②重写Thread类的run方法 , 把自定义线程的任务代码写在run方法中
③创建Thread的子类对象,并且调用start方法开启线程。

重写run方法的目的:
每个线程都有自己的任务代码,jvm创建的主线程的任务代码就是main方法中的所有代码, 自定义线程的任务代码就写在run方法中,自定义线程负责了run方法中代码。

注意:一个线程一旦开启,那么线程就会执行run方法中的代码,run方法千万不能直接调用,直接调用run方法就相当调用了一个普通的方法而已,并没有开启新的线程。

public class Demo1 extends Thread {
    
    @Override  //把自定义线程的任务代码写在run方法中。
    public void run() {
        for(int i  = 0 ; i < 100 ; i++){
            System.out.println("自定义线程:"+i);
        }
    }
    
    public static void main(String[] args) {
        //创建了自定义的线程对象。
        Demo1 d = new Demo1();
        //调用start方法启动线程
        d.start();
        
        for(int i  = 0 ; i < 100 ; i++){
            System.out.println("main线程:"+i);
        }
    }

}

2.方式二:实现Runnable接口

步骤:

  1. 自定义一个类实现Runnable接口。
  2. 实现Runnable接口的run方法,把自定义线程的任务定义在run方法上。
  3. 创建Runnable实现类对象。
  4. 创建Thread类的对象,并且把Runnable实现类的对象作为实参传递。
  5. 调用Thread对象的start方法开启一个线程。

问题一:Runnable实现类的对象是线程对象吗?
Runnable实现类的对象并不是一个线程对象,只不过是实现了Runnable接口的对象而已。只有是Thread或者是Thread的子类才是线程对象。

问题二:为什么要把Runnable实现类的对象作为实参传递给Thread对象呢?作用是什么?
作用就是把Runnable实现类的对象的run方法作为了线程的任务代码去执行了。

推荐使用:实现Runable接口,因为java是单继承,多实现。

public class Demo3 implements Runnable{

    @Override
    public void run() {
        /*System.out.println("this:"+ this);
        System.out.println("当前线程:"+ Thread.currentThread());*/
        for(int i = 0 ; i < 100 ; i++){
            System.out.println(Thread.currentThread().getName()+":"+i);
        }
    }
    
    public static void main(String[] args) {
        //创建Runnable实现类的对象
        Demo3 d = new Demo3();
        //创建Thread类的对象, 把Runnable实现类对象作为实参传递。
        Thread thread = new Thread(d,"晓红");  //Thread类使用Target变量记录了d对象,
        //调用thread对象的start方法开启线程。
        thread.start();

        for(int i = 0 ; i < 100 ; i++){
            System.out.println(Thread.currentThread().getName()+":"+i);
        }
        
    } 
    
    /*
      Thread类 的run方法
      
     *  @Override
        public void run() {
            if (target != null) {
                target.run();  //就相当于Runnable实现类的对象的run方法作为了Thread对象的任务代码了。
            }
        }
    */
}

三、常见的线程方法

package com.hcx.thread;

public class Demo extends Thread {
    
    public Demo(String name){
        super(name); //调用了Thread类的一个参数的构造方法。
    }
    
    @Override
    public void run() {
        System.out.println("this:"+ this); //this:Thread[hcx,10,main]
        System.out.println("当前线程对象:" + Thread.currentThread());//当前线程对象:Thread[hcx,10,main]
        
        for (int i = 0; i < 10 ; i++) {
            System.out.println(Thread.currentThread().getName()+":"+i);
            
            /*try {
                Thread.sleep(100);  //在这里不能抛出异常,只能捕获: Thread类的run方法没有抛出异常类型,所以子类不能抛出异常类型。
            } catch (InterruptedException e) {
                e.printStackTrace();
            } */
        }
    
    }
    
    public static void main(String[] args) throws InterruptedException {
        //创建了一个线程对象
        Demo d = new Demo("hcx");
        d.setPriority(10); //设置线程的优先级。优先级的数字越大,优先级越高 ,优先级的范围是1~10
        d.start();
        
        for (int i = 0; i < 10 ; i++) {
            System.out.println(Thread.currentThread().getName()+":"+i);
        }
        
        /*
        System.out.println("自定义线程的优先级:"+d.getPriority());  //线程的优先级默认是5
        System.out.println("主线程的优先级:"+Thread.currentThread().getPriority());
        
        
        d.start();
        
        d.setName("js_hcx"); //setName设置线程的名字
        d.start(); //开启线程 
        
        Thread mainThread = Thread.currentThread();
        System.out.println("主线程的名字:"+ mainThread.getName());
    */
    }


}

四、线程安全问题及解决方法

1.线程安全问题的出现

需求:模拟三个窗口同时售卖50张票

注意:票数tickets是共享的,需要给三个线程对象使用,需要使用static修饰。

class SaleTickets extends Thread{
    static int tickets = 50;
    @Override
    public void run() {
        while(tickets>0){
            System.out.println("卖到了第"+tickets+"张");
            tickets--;
        }
    }
}

public class Demo2 {
    
    public static void main(String[] args) {
        SaleTickets thread1 = new SaleTickets();
        SaleTickets thread2 = new SaleTickets();
        SaleTickets thread3 = new SaleTickets();
        
        thread1.start();
        thread2.start();
        thread3.start();
    }

}

问题:出现了线程安全问题

线程安全问题出现的根本原因:
①存在两个或者两个以上的线程对象共享一个资源。
②多线程操作共享资源的代码有多句。

解决:sun提供了线程同步机制让我们解决该类问题

2.线程安全问题的解决方式

java线程同步机制的方式:

方式一:同步代码块

格式:

synchronized(锁对象){
    需要被同步的代码...
}

同步代码块要注意事项:

  1. 任意的一个对象都可以做为锁对象。
  2. 在同步代码块中调用了sleep方法并不是释放锁对象的。
  3. 只有真正存在线程安全问题的时候才使用同步代码块,否则会降低效率的。
  4. 多线程操作的锁对象必须是唯一共享的。否则无效。

使用同步代码块解决:

package com.hcx.thread;

class SaleTickets extends Thread{
    //票数  如果是非静态的成员变量,非静态的成员变量数据是在每个对象中都会维护一份数据的。
    static int tickets = 50;
    
    public SaleTickets(String name) {
        super(name);
    }
    @Override
    public void run() {
        while(true){
            //同步代码块
            synchronized ("锁") {                
                if(tickets>0){
                    System.out.println(Thread.currentThread().getName()+"售出了第"+tickets+"号票");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    tickets--;
                }else{
                    System.out.println("售罄了..");
                    break;
                }
            }
        }
    }
}

public class Demo2 {
    
    public static void main(String[] args) {
        SaleTickets thread1 = new SaleTickets("窗口1");
        SaleTickets thread2 = new SaleTickets("窗口2");
        SaleTickets thread3 = new SaleTickets("窗口3");
        
        thread1.start();
        thread2.start();
        thread3.start();
    }

}

注意:任意的对象都可以作为锁对象,凡是对象内部维护了一个状态的,java同步机制就是使用了对象中的状态作为了锁的标识。

使用runnable接口的方式:

class SaleTicket implements Runnable{
    
    int  tickets = 50; // 票数
    
    @Override
    public void run() {
        while(true){
            synchronized ("锁") {
                if(tickets>0){
                    System.out.println(Thread.currentThread().getName()+"售出了第"+ tickets+"号票");
                    tickets--;
                }else{
                    System.out.println("售罄了..");
                    break;
                }   
            }
        }       
    }
}

public class Demo4 {
    
    public static void main(String[] args) {
        //创建了一个Runnable实现类的对象
        SaleTicket saleTicket = new SaleTicket();
        //创建三个线程对象模拟三个窗口
        Thread thread1 = new Thread(saleTicket,"窗口1");
        Thread thread2 = new Thread(saleTicket,"窗口2");
        Thread thread3 = new Thread(saleTicket,"窗口3");
        //开启线程售票
        thread1.start();
        thread2.start();
        thread3.start();

    }

}

方式二:同步函数

同步函数就是使用synchronized修饰一个函数。

同步函数要注意的事项 :

  1. 如果是一个非静态的同步函数的锁对象是this对象,如果是静态的同步函数的锁对象是当前函数所属的类的字节码文件(class对象)。
  2. 同步函数的锁对象是固定的,不能由你来指定的。
class BankThread extends Thread{
    
    static  int count = 5000;
    
    public BankThread(String name){
        super(name);
    }
    
    @Override  //
    public synchronized  void run() {
        while(true){
            synchronized ("锁") {            
                if(count>0){
                    System.out.println(Thread.currentThread().getName()+"取走了1000块,还剩余"+(count-1000)+"元");
                    count= count - 1000;
                }else{
                    System.out.println("取光了...");
                    break;
                }
            }
        }
    }   
    
    
    //静态的函数---->函数所属 的类的字节码文件对象--->BankThread.class  唯一的。
    public static synchronized  void getMoney(){
        
    }
    
}

public class Demo1 {

    public static void main(String[] args) {
        //创建两个线程对象
        BankThread thread1 = new BankThread("小红");
        BankThread thread2 = new BankThread("小明");
        //调用start方法开启线程取钱
        thread1.start();
        thread2.start();
    }
    
}

静态函数的锁对象:

静态函数的锁对象.png

推荐使用: 同步代码块。
原因:

四、死锁

java中同步机制解决了线程安全问题,但是也同时引发死锁现象。

死锁现象出现的根本原因:

  1. 存在两个或者两个以上的线程。
  2. 存在两个或者两个以上的共享资源。

死锁现象的解决方案:没有方案,只能尽量避免发生而已。

class DeadLock extends Thread{
    
    public DeadLock(String name){
        super(name);
    }
    public void run() {
        if("张三".equals(Thread.currentThread().getName())){
            synchronized ("遥控器") {
                System.out.println("张三拿到了遥控器,准备去拿电池");
                synchronized ("电池") {
                    System.out.println("张三拿到了遥控器与电池了,开着空调吹着");
                }
            }
        }else if("李四".equals(Thread.currentThread().getName())){
            synchronized ("电池") { 
                System.out.println("李四拿到了电池,准备去拿遥控器");
                synchronized ("遥控器") {
                    System.out.println("李四拿到了遥控器与电池了,开着空调吹着");
                }
            }
        }   
    }
}

public class Demo2 {

    public static void main(String[] args) {
        DeadLock thread1 = new DeadLock("张三");
        DeadLock thread2 = new DeadLock("李四");
        //开启线程
        thread1.start();
        thread2.start();
    }
}

五、线程的通讯

一个线程完成了自己的任务时,要通知另外一个线程去完成另外一个任务.

常用方法:

wait与notify方法要注意的事项:

  1. wait方法与notify方法是属于Object对象的。
  2. wait方法与notify方法必须要在同步代码块或者是同步函数中才能 使用。
  3. wait方法与notify方法必需要由锁对象调用。

生产者与消费者:

生产者与消费者.png

为什么这些方法定义在Object类中?

因为这些方法在操作线程时,都必须要标识他们所操作线程持有的锁,只有同一个锁上的被等待线程,可以被统一锁上notify唤醒,不可以对不同锁中的线程进行唤醒,就是等待和唤醒必须是同一个锁。而锁由于可以使任意对象,所以可以被任意对象调用的方法定义在Object类中。

wait()和sleep()的区别:

//产品类
class Product{
    
    String name;  //名字
    
    double price;  //价格
    
    boolean flag = false; //产品是否生产完毕的标识,默认情况是没有生产完成。
    
}

//生产者
class Producer extends Thread{
    
    Product  p ;    //产品
    
    public Producer(Product p) {
        this.p  = p ;
    }
    
    @Override
    public void run() {
        int i = 0 ; 
        while(true){
         synchronized (p) {
            if(p.flag==false){
                 if(i%2==0){
                     p.name = "苹果";
                     p.price = 6.5;
                 }else{
                     p.name="香蕉";
                     p.price = 2.0;
                 }
                 System.out.println("生产者生产出了:"+ p.name+" 价格是:"+ p.price);
                 p.flag = true;
                 i++;
                 p.notifyAll(); //唤醒消费者去消费
            }else{
                //已经生产完毕,等待消费者先去消费
                try {
                    p.wait();   //生产者等待
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }   
      } 
    }
}


//消费者
class Customer extends Thread{
    
    Product p; 
    
    public  Customer(Product p) {
        this.p = p;
    }
    
    
    @Override
    public void run() {
        while(true){
            synchronized (p) {  
                if(p.flag==true){  //产品已经生产完毕
                    System.out.println("消费者消费了"+p.name+" 价格:"+ p.price);
                    p.flag = false; 
                    p.notifyAll(); // 唤醒生产者去生产
                }else{
                    //产品还没有生产,应该 等待生产者先生产。
                    try {
                        p.wait(); //消费者也等待了...
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }   
    }
}

public class Demo {
    
    public static void main(String[] args) {
        Product p = new Product();  //产品
        //创建生产对象
        Producer producer = new Producer(p);
        //创建消费者
        Customer customer = new Customer(p);
        //调用start方法开启线程
        producer.start();
        customer.start();
    }
    
}

wait():一个线程如果执行了wait方法,那么该线程就会进去一个以锁对象为标识符的线程池中等待
notify():如果一个线程执行了notify方法,那么就会唤醒以锁对象为标识符的线程池中等待线程中的其中一个。

线程的停止:

public class Demo extends Thread {
    
    boolean flag = true;
    
    public Demo6(String name){
        super(name);
    }
    
    @Override
    public synchronized void run() {
        int i = 0 ;
        while(flag){
            try {
                this.wait(); //小红等待..
            
            } catch (InterruptedException e) {
                System.out.println("接收到了异常了");
            }
            System.out.println(Thread.currentThread().getName()+":"+i);
            i++;
        }
    }
    
    public static void main(String[] args) {
        Demo d = new Demo("小红");
        d.setPriority(10);
        d.start();
        
        for(int i = 0 ; i<100 ; i++){
            System.out.println(Thread.currentThread().getName()+":"+i);
            //当主线程的i是80的时候停止小红线程。
            //d.interrupt();  // interrupt()根本就是无法停止一个线程。
            if(i==80){
                d.flag = false;
                d.interrupt(); //把线程的等待状态强制清除,被清除状态的线程会接收到一个InterruptedException。 
                /*synchronized (d) {                    
                    d.notify();
                }*/
            }
        }
    }
}

六、线程的生命周期

线程的生命周期.png

七、后台线程(守护线程)

守护线程(后台线程):在一个进程中如果只剩下了守护线程,那么守护线程也会死亡。

一个线程默认都不是守护线程。

public class Demo7 extends Thread {
    
    public Demo7(String name){
        super(name);
    }
    
    @Override
    public void run() {
        for(int i = 1 ; i<=100 ; i++){
            System.out.println("更新包目前下载"+i+"%");
            if(i==100){
                System.out.println("更新包下载完毕,准备安装..");
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
    public static void main(String[] args) {
         Demo7 d = new Demo7("后台线程");
         d.setDaemon(true); //setDaemon() 设置线程是否为守护线程,true为守护线程, false为非守护线程。
        // System.out.println("是守护线程吗?"+ d.isDaemon()); //判断线程是否为守护线程。
         d.start();
         
         for(int i = 1 ; i<=100 ; i++){
             System.out.println(Thread.currentThread().getName()+":"+i);
         }
         
    }

}

join方法: 加入

当A线程执行到了B线程Join方法时A就会等待,等B线程都执行完A才会执行,Join可以用来临时加入线程执行。

//妈妈
class  Mon extends Thread{
    
    public void run() {
        System.out.println("妈妈洗菜");
        System.out.println("妈妈切菜");
        System.out.println("妈妈准备炒菜,发现没有酱油了..");
        //叫儿子去打酱油
        Son s= new Son();
        s.start();
        try {
            s.join();  //加入。 一个线程如果执行join语句,那么就有新的线程加入,执行该语句的线程必须要让步给新加入的线程先完成任务,然后才能继续执行。
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        System.out.println("妈妈继续炒菜");
        System.out.println("全家一起吃饭..");     
    }
} 

class Son extends Thread{
    
    @Override
    public void run() {
        System.out.println("儿子下楼..");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("儿子一直往前走");
        System.out.println("儿子打完酱油了");
        System.out.println("上楼,把酱油给老妈");
    }
}

public class Demo {
    
    public static void main(String[] args) {
        Mon m = new Mon();
        m.start();
    }
}

上一篇 下一篇

猜你喜欢

热点阅读