学习笔记之线程
多线程
一、实现多线程
进程
是正在运行的程序
- 是系统进行资源分配和调用的独立单位
 - 每一个进程都有它自己的内存空间和系统资源
 
线程
是进程中的单个顺序控制流,是一条执行路径
- 单线程:一个进程如果只有一条执行路径,则称为单线程程序

 - 多线程:一个进程如果有多条执行路径,则称为多线程程序

 
实现多线程方式:
- 继承Thread类
- 定义一个类MyThread继承Thread类
 - 在MyThread类中重写run()方法
 - 创建MyThread类的对象
 - 启动线程
 
 
注:run()用来封装线程执行的代码。
run():封装线程执行的代码,直接调用,相当于普通方法的调用。
strat():启动线程;然后有JVM调用此线程的run()方法。
Thread类中的方法:设置和获取线程名称
- void setName(String name):将此线程的名称更改为参数name
 - 也可以通过构造方法来设置
 - String getName():返回此线程的名称
 - public static Thread currentThread():返回对当前正在执行的线程对象的引用
 
public class MyThread extends Thread {
    MyThread(){}
    MyThread(String name){
        super(name);
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++){
            System.out.println(getName()+","+i);
        }
    }
}
public class MyThreadDemo {
    public static void main(String[] args) {
        //通过set方法设置线程名称
//        MyThread mt = new MyThread();
//        MyThread mt2 = new MyThread();
//
//        mt.setName("A:");
//        mt2.setName("B:");
////        mt.run();//直接调用
////        mt2.run();
//        mt.start();
//        mt2.start();//启动线程,JVM调用run方法
        //通过构造方法设置:
        MyThread mt = new MyThread("A:");
        MyThread mt2 = new MyThread("B:");
        mt.start();
        mt2.start();
        //static Thread currenThread()返回当前正在执行的线程对象的引用
        System.out.println(Thread.currentThread().getName());    // main
    }
}
线程调度
两种线程调度模型:
- 分时调度模型:所有线程轮流使用CPU的使用权,平均分配每个线程占用CPU的时间片。
 - 抢占式调度模型:优先让优先级高的线程使用CPU。如果线程的优先级相同,那么会随机选择一个,优先级高的线程获取的CPU时间片相对多一些。(java)。
 
Thread类中设置和获取线程优先级的方法
- public final int getPriority():返回此线程的优先级。
 - public final void setPriority(int newPriority):更改此线程的优先级(线程优先级的范围是1-10,默认为5)。
 
线程优先级高仅仅表示线程获取CPU时间片的几率高,但是要在次数比较多,或者多次运行的时候才能看到你想要的效果。
public class ThreadPriority extends Thread{
    ThreadPriority(){}
    ThreadPriority(String name){
        super(name);
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++){
            System.out.println(getName()+":"+i);
        }
    }
}
public class Demo {
    public static void main(String[] args) {
        ThreadPriority tp = new ThreadPriority("A:");
        ThreadPriority tp2 = new ThreadPriority("B:");
        ThreadPriority tp3 = new ThreadPriority("C:");
        System.out.println(Thread.MIN_PRIORITY);//1
        System.out.println(Thread.NORM_PRIORITY);//5
        System.out.println(Thread.MAX_PRIORITY); // 10
        System.out.println("--------------------------------");
        System.out.println(tp.getPriority());//5
        System.out.println(tp2.getPriority());//5
        System.out.println(tp3.getPriority());//5
        System.out.println("-------------------------");
        //设置优先级
        //public final void setPriority(int newPriority):更改此线程的优先级
        tp.setPriority(5);
        tp2.setPriority(10);
        tp3.setPriority(1);
        System.out.println(tp.getPriority());//5
        System.out.println(tp2.getPriority());//10
        System.out.println(tp3.getPriority());//1
        System.out.println("-------------------");
        tp.start();
        tp2.start();
        tp3.start();
    }
}
线程控制
方法:
- static void sleep(long millis):使当前正在执行的线程停留(暂停执行)指定的毫秒数
 - void join():等待这个线程死亡
 - void setDaemon(boolean on)将此线程标记为守护线程,当运行的线程是守护线程时,JAVA虚拟机将退出
 
sleep
public class Sleep extends Thread{
    Sleep(){}
    Sleep(String name){
        super(name);
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++){
            System.out.println(getName()+i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public class SleepDemo {
    public static void main(String[] args) {
        Sleep s = new Sleep("A");
        Sleep s2 = new Sleep("B");
        Sleep s3 = new Sleep("C");
        s.start();
        s2.start();
        s3.start();
    }
}
join
public class JoinDemo {
    public static void main(String[] args) {
        //雍正,胤禩是康熙的儿子 。雍正、胤禩要继承皇位得康熙退位
//        void join():等待这个线程死亡-->康熙
        Join j = new Join("康熙");
        Join j2 = new Join("雍正");
        Join j3 = new Join("胤禩");
        j.start();
        try {
            j.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        j2.start();
        j3.start();
    }
}
public class Join extends Thread{
    Join(){}
    Join(String name){
        super(name);
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++){
            System.out.println(getName()+i);
        }
    }
}
setDaemon
public class SetDaemon extends Thread{
    public SetDaemon() {
    }
    public SetDaemon(String name) {
        super(name);
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++){
            System.out.println(getName()+i);
        }
    }
}
public class SetDaemonDemo {
    public static void main(String[] args) {
        //结拜兄弟 同年同月同日死
        SetDaemon sd2 = new SetDaemon("虚竹");
        SetDaemon sd3 = new SetDaemon("段誉");
        //设置为主线程
        Thread.currentThread().setName("乔峰");
        //设置为守护线程
        sd2.setDaemon(true);
        sd3.setDaemon(true);
        sd2.start();
        sd3.start();
        for (int i = 0; i < 10; i++){
            System.out.println(Thread.currentThread().getName()+i);
        }
    }
}
线程生命周期

实现Runnable接口实现多线程
- 定义一个类MyRunnable实现Runnable接口
 - 实现MyRunnable类中的run()方法
 - 创建MyRunnable类的对象
 - 创建Thread类的对象,把MyRunnable对象作为构造方法的参数
 - 启动线程
 
多线程的两种方式:
- 继承Thread类
 - 实现Runnable接口
 
实现Runnable接口:避免了Java单继承的局限性,适合多个相同程序的代码去处理同一个资源的情况,把线程和程序的代码、数据有效分离,较好的体现了面向对象的设计思路
public class MyRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 100; i++){
            System.out.println(Thread.currentThread().getName()+i);
        }
    }
}
public class MyRunnableDemo {
    public static void main(String[] args) {
        //创建MyRunnable类的对象
        MyRunnable mr = new MyRunnable();
        //创建Thread类的对象,把MyRunnable对象作为构造方法的参数
        Thread t1 = new Thread(mr,"A");
        Thread t2 = new Thread(mr,"B");
        //启动线程
        t1.start();
        t2.start();
    }
}
线程同步
卖票
public class SellTicket implements Runnable {
    private int Ticket = 100;
    @Override
    public void run() {
        while (true) {
            if (Ticket > 0) {
                try {
                    Thread.sleep(100); //模拟卖票间隔时间
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "售卖第" + Ticket + "张票");
                Ticket--;
            }
        }
    }
}
public class Demo {
    public static void main(String[] args) {
        SellTicket st = new SellTicket();
        Thread t = new Thread(st, "一号窗口:");
        Thread t2 = new Thread(st, "二号窗口");
        Thread t3 = new Thread(st, "三号窗口");
        t.start();
        t2.start();
        t3.start();
    }
}
因为线程执行的随机性
- 出现重票
 - 出现负数票
 
解决
判断多线程程序是否会有数据安全问题的标准
- 是否是多线程环境
 - 是否有共享数据
 - 是否有多条语句操作共享数据
 
解决思路
- 破坏安全环境
实现: - 将多条语句操作共享数据的代码锁起来,让任意时刻只能有一个线程执行(同步代码块)
 - 格式:
 
synchronized(任意对象){
    多条语句操作共享数据的代码
}
public class SellTicket implements Runnable {
    private int Ticket = 100;
    private Object obj = new Object();
    @Override
    public void run() {
        synchronized (obj) {
            while (true){
                if (Ticket > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "窗口正在售卖第" + Ticket + "张票");
                    Ticket--;
                }
            }
        }
    }
}
public class SellTicketDemo {
    public static void main(String[] args) {
        SellTicket st = new SellTicket();
        Thread t = new Thread(st, "一号");
        Thread t2 = new Thread(st, "二号");
        Thread t3 = new Thread(st, "三号");
        t.start();
        t2.start();
        t3.start();
    }
}
优缺点:
- 解决了多线程的安全问题
 - 当线程很多时,因为每个线程都会去判断同步上的锁,这很耗费资源,降低了程序的运行效率
 
同步方法
同步方法:将synchronized关键字加到方法上
- 格式:
修饰符synchronized返回值类型方法名(参数)
同步方法的锁对象: - this
 
public class SellTicket implements Runnable {
    private int Ticket = 100;
    private int x = 0;
    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                if (Ticket > 100) {
                    if (x % 2 == 0) {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName() + "窗口正在售卖第" + Ticket + "张票");
                        Ticket--;
                    } else {
                        sellTicket();
                    }
                    x++;
                }
            }
        }
    }
    private synchronized void sellTicket() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "窗口正在售卖第" + Ticket + "张票");
        Ticket--;
    }
}
同步静态方法:就是把synchonized关键字加到静态方法上
- 格式:
- 修饰符 static synchronized 返回值类型 方法名(方法参数){}
同步静态方法的锁对象 
 - 修饰符 static synchronized 返回值类型 方法名(方法参数){}
 - 类名+class
 
线程安全的类
- StringBuffer
- 如果要操作少量的数据用 = String
 - 单线程操作字符串缓冲区 下操作大量数据 = StringBuilder
 - 多线程操作字符串缓冲区 下操作大量数据 = StringBuffer
 
 - Vector
- Vector与ArrayList一样,也是通过数组实现的,不同的是它支持线程的同步,即某一时刻只有一个线程能够写Vector,避免多线程同时写而引起的不一致性,但实现同步需要很高的花费,因此,访问它比访问ArrayList慢。
 
 - Hashtable
Collections类中的synchronizedList(ListList)可以返回线程安全的列表、synchronizedMap(Map<K,V> m)可以返回线程安全的映射、......  
Lock锁(JDK5之后)
- Lock实现提供比使用synchronized方法和语句获得更多广泛的锁定操作
 
- Lock中提供了获得锁和释放锁的方法
- void lock():获得锁
 - void unlock():释放锁
 
 
- Lock是接口不能直接实例化,这里采用它实现的类ReentrantLock来实例化
 
- ReentrantLock的构造方法
- ReentrantLock():创建一个ReentrantLock的实例
 
 
mport java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class SellTicket implements Runnable{
    private int Ticket = 100;
    private Lock lock = new ReentrantLock();
    @Override
    public void run() {
        while (true){
            try {
                lock.lock();
                if (Ticket > 0){
                    System.out.println(Thread.currentThread().getName()+"窗口正在售卖第"+Ticket+"张票");
                    Ticket--;
                }
            }finally { //用finally来保证必定释放锁
                lock.unlock();
            }
        }
    }
}
public class SellTicketDemo {
    public static void main(String[] args) {
        SellTicket st = new SellTicket();
        Thread t = new Thread(st, "一号");
        Thread t2 = new Thread(st, "二号");
        Thread t3 = new Thread(st, "三号");
        t.start();
        t2.start();
        t3.start();
    }
}
生产者消费者
- 生产者消费者问题,实际上主要包括了两类线程:
 
- 一类是生产者线程用于生产数据
 - 一类是消费者线程用于消费数据
 
- 为了解耦生产者和消费者的关系,通常会采用共享数据区域,就像是一个仓库
 
- 生产者生产数据之后直接放置在共享数据中,并不需要关心消费者的行为
 - 消费者只需要从共享数据区中去获取数据,并不需要关心生产者的行为
 
生产者----->共享数据区域<-------消费者
- 为体现生产和消费过程的等待和唤醒,java就提供了几个方法供我们使用,这几个方法在Object类中Object类的等待和唤醒方法:
 
- void wait()导致当前线程等待,知道另一个线程调用该对象的notify()方法或notifyAll()方法
 - void notify()唤醒正在等待对象监视器的单个线程
 - void notifyAll()唤醒正在等待对象监视器的所有线程
 
/*
生产者消费者案例:
奶箱(Box)定义一个成员变量,表示第x瓶奶,提供存储牛奶和获取牛奶的操作
生产者(Producer):实现Runnable接口,实现run()方法,调用存储牛奶的操作
消费者(Customer):实现Runnable接口,实现run()方法,调用获取牛奶操作‘
测试类(Demo):里面有main方法,main方法中的代码步骤如下:
    1.创建奶箱对象,这是共享数据区域
    2.创建生产者对象,把奶箱对象作为构造方法参数传递,因为在这个类中要调用存储牛奶操作
    3.创建消费者对象,把奶箱对象作为构造方法参数传递,因为在这个类中要调用存储牛奶操作
    4.创建两个线程对象,分别把生产者对象和消费者对象作为构造方法参数传递
    5.启动线程
 */
 public class Box {
    private int milk;
    private boolean x = false;//牛奶箱的状态,没有牛奶
    public synchronized void put(int mike){
        //如果有奶等待消费
        if (x){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.milk = mike;
        System.out.println("员工放入"+milk+"瓶奶");
        x = true;
        notify();
    }
    public synchronized void get(){
        //如果没有牛奶等待生产
        if (!x){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("用户拿到"+milk+"瓶奶");
        x = false;
        notify();
    }
}
public class Producer implements Runnable{
    Box b;
    public Producer(Box b) {
        this.b = b;
    }
    @Override
    public void run() {
        for (int i = 0; i < 5; i++){
            b.put(i+1);
        }
    }
}
public class Customer implements Runnable{
    Box b;
    public Customer(Box b) {
        this.b = b;
    }
    @Override
    public void run() {
        while (true){
            b.get();
        }
    }
}
public class Demo {
    public static void main(String[] args) {
        Box b = new Box();
        Producer p = new Producer(b);
        Customer c = new Customer(b);
        Thread t = new Thread(p);
        Thread t2 = new Thread(c);
        t.start();
        t2.start();
    }
}

                
            
        
浙公网安备 33010602011771号