一、线程的特点

1.线程的分类

  java中的线程分为两类:守护线程用户线程。唯一的区别是判断JVM何时离开。

  守护线程是用来服务用户线程的,通过在start()方法前调用Thread.setDaemon(true)可以把一个用户线程变成一个守护线程。

  java垃圾回收就是一个典型的守护线程;若JVM中都是守护线程,当前JVM将退出。

2.线程的生命周期

3.线程的同步机制

(1)线程的安全问题

  在上一篇随笔中,多窗口售票的程序代码存在线程的安全问题,打印车票会出现重票、错票。

  安全问题存在的原因:

    由于一个线程在操作共享数据时,未执行完毕的情况下就有另外的线程参与进来,导致共享数据存在了安全问题。

  解决方法:

    让一个线程操作共享数据完毕后,其他线程才有机会参与共享数据的操作,即采用同步机制

(2)方法一:同步代码块

synchronized(同步监视器){
    //需要被同步的代码块(即为操作共享数据的代码)
}

同步监视器:由任意一个类的对象来充当,哪个线程获取此监视器,谁就执行大括号里被同步的代码,俗称:锁。

要求:

  所有线程必须共用同一把锁。

  在实现的方式中可以用this来当同步锁,在继承的方式中慎用this,因为this将指向不同的对象。

多窗口售票代码案例

class Window implements Runnable{
    int ticket = 100;//共享数据
    Object obj = new Object();//创建一个对象,作为同步锁。
    public void run(){
        //Object obj = new Object();注意不能在这里创建,局部变量起不到同步控制的作用。
        while(true){
            synchronized(obj){//同步控制,obj作为锁,也可以用this
                if(ticket > 0){
                    System.out.println(Thread.currentThread().getName()+"售票,票号为:" + ticket--);
                }else{
                    break;
                }
            }
        }
    }
}

 

(3)方法二:同步方法

将操作共享数据的方法声明为synchronized,能够保证当一个线程执行此方法时,其他线程在外等待直至此线程执行完此方法。

同步锁:this(即调用该方法的对象,所以只适用实现的多线程方法,不适用于继承的多线程方法)

多窗口售票代码案例

class Window implements Runnable{
    int ticket = 100;//共享数据
    public void run(){
        while(true) {
            show();
        }
    }
    public synchronized void show() {
        if (ticket > 0) {
            try {
                Thread.currentThread().sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "售票,票号为:" + ticket--);
        } 
    }
}

(4)单例模式懒汉式的线程安全问题:使用同步机制

注意:对于一般的方法可以使用this当同步锁;但对于静态方法就没办法使用this,而是使用当前类本身充当锁。

public class Singleton {
    private Singleton(){
        
    }
    
    private static Singleton instance = null;
    
    public static Singleton getInstance() {
        synchronized (Singleton.class) {//注意静态方法的同步锁使用类本身
            if (instance == null) {
                instance = new Singleton();
            }
        }
        return instance;
    }
}

(5)释放同步锁的操作:

  同步代码块、同步方法中执行了线程对象的wait()方法,当前线程暂停,并释放锁。

(6)不释放锁的操作:

  Thread.sleep()、Thread.yield()暂停当前线程的执行,但不会释放锁。

 

(7)线程同步练习

有两个储户分别向同一个账户存3000元,每次存1000元,每次存完打印账户余额。(存在线程安全问题)

class Account{
    double balance;
    
    public Account() {
        
    }
    //存钱
    public synchronized void deposit(double amt) {
        balance += amt;
        try {
            Thread.currentThread().sleep(100);//为了让错误暴露出来
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+":"+balance);
    }
}

class Customer extends Thread{
    Account account;
    public Customer(Account account) {
        this.account = account;
    }
    @Override
    public void run() {
        for(int i = 0;i < 3; i++) {
            account.deposit(1000);
        }
    }
}
public class Test{
    public static void main(String[] args) {
        Account a = new Account();
        Customer c1 = new Customer(a);
        Customer c2 = new Customer(a);
        c1.setName("");
        c2.setName("");
        c1.start();
        c2.start();
    }

}
 

 (8)死锁的问题

不同的线程分别占用对方需要的同步资源不放弃,都在等待对方放弃自己需要的资源,就形成了死锁。

代码案例: 

public class Test{
    //两个同步资源
    static StringBuffer sb1 = new StringBuffer();
    static StringBuffer sb2 = new StringBuffer();
    
    public static void main(String[] args) {
        new Thread(){
            public void run(){
                synchronized(sb1){//得到同步锁sb1
                    try{
                        Thread.currentThread().sleep(10);//通过sleep将问题暴露出来
                    }catch(InterruptedException e){
                        e.printStackTrace();
                    }
                    sb1.append("A");
                    synchronized(sb2){//得不到同步锁sb2
                        sb2.append("B");
                        System.out.println(sb1);
                        System.out.println(sb2);
                    }
                }
            }
        }.start();
        
        new Thread(){
            public void run(){
                synchronized(sb2){//得到同步锁sb2
                    try{
                        Thread.currentThread().sleep(10);
                    }catch(InterruptedException e){
                        e.printStackTrace();
                    }
                    sb1.append("C");
                    synchronized(sb1){//得不到同步锁sb1
                        sb2.append("D");
                        System.out.println(sb1);
                        System.out.println(sb2);
                    }
                }
            }
        }.start();
    }
}

(9)线程的通信

wait():令当前线程挂起并放弃CPU、同步资源,排队等候再次对资源的访问。 

notify() / notifyAll():唤醒一个或所有正在排队等候同步资源的线程,一个是指优先级最高的线程。

java.lang.Object提供的这三个方法只有在synchronized代码块或synchronized方法中才能使用,否则报异常。

代码案例:

  使用两个线程交替打印1-100。

class PrintNum implements Runnable{
    int num = 1;
    public void run(){
        while(true){
            synchronized(this){
                notify();//唤醒另一个线程,等待p的获得
                if(num <= 100){
                    System.out.println(Thread.currentThread().getName()+num);
                    num++;
                }else{
                    break;
                }
                try{
                    wait();//挂起,释放p
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
        }
    }
}
public class Test{
    
    public static void main(String[] args) {
        PrintNum p = new PrintNum();
        Thread t1 = new Thread(p);
        Thread t2 = new Thread(p);
        t1.setName("");
        t2.setName("");
        t1.start();
        t2.start();
    }
}

 (10)生产者消费者问题

  生产者(producer)将产品交给店员(Clerk),由消费者(Customer)从店员取走商品。店员最多只能保存20件商品,如果生产者试图生产更多商品,店员会通知生产者停止生产,店中有空位放产品再通知生产者开始生产;如果店中没有产品,店员通知消费者等一下,有产品再通知消费者取走产品。

class Clerk{
    int product = 0;
    
    public synchronized void addProduct(){
        if(product < 20){
            product++;
            System.out.println(Thread.currentThread().getName()+"生产了第"+product+"件产品");
            notifyAll();
        }else{
            try{
                wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
    }
    public synchronized void consumeProduct(){
        if(product > 0){
            product--;
            System.out.println(Thread.currentThread().getName()+"消费了第"+product+"件产品");
            notifyAll();
        }else{
            try{
                wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}

class Producer implements Runnable{
    Clerk clerk = null;
    public Producer(Clerk clerk){
        this.clerk = clerk;
    }
    public void run(){
        System.out.println("生产者开始生产产品");
        while(true){
            try{
                Thread.currentThread().sleep(100);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            clerk.addProduct();
        }
    }
}

class Customer implements Runnable{
    Clerk clerk = null;
    public Customer(Clerk clerk){
        this.clerk = clerk;
    }
    public void run(){
        System.out.println("消费者开始消费产品");
        while(true){
            try{
                Thread.currentThread().sleep(300);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            clerk.consumeProduct();
        }    
    }
}

public class Test{
    public static void main(String[] args){
        Clerk c = new Clerk();
        Producer p1 = new Producer(c);
        Customer c1 = new Customer(c);
        Thread t1 = new Thread(p1);
        Thread t2 = new Thread(p1);
        Thread t3 = new Thread(c1);
        t1.setName("生产者1号");
        t2.setName("生产者2号");
        t3.setName("消费者1号");
        t1.start();
        t2.start();
        t3.start();
    }
}