第十一章:Java_多线程

来源:互联网 发布:淘宝设置精品橱窗推荐 编辑:程序博客网 时间:2024/05/16 16:13

1.理解程序、进程、线程的概念

程序可以理解为静态的代码
进程可以理解为执行中的程序。
线程可以理解为进程的进一步细分,程序的一条执行路径

每个Java程序都有一个隐含的主线程: main 方法

使用多线程的优点:

这里写图片描述

Thread的常用方法:

/* * Thread的常用方法: * 1.start():启动线程并执行相应的run()方法 * 2.run():子线程要执行的代码放入run()方法中 * 3.currentThread():静态的,调取当前的线程 * 4.getName():获取此线程的名字 * 5.setName():设置此线程的名字 * 6.yield():调用此方法的线程释放当前CPU的执行权 * 7.join():在A线程中调用B线程的join()方法,表示:当执行到此方法,A线程停止执行,直至B线程执行完毕, * A线程再接着join()之后的代码执行 * 8.isAlive():判断当前线程是否还存活 * 9.sleep(long l):显式的让当前线程睡眠l毫秒 * 10.线程通信:wait()   notify()  notifyAll() *  * 设置线程的优先级 * getPriority() :返回线程优先值    setPriority(int newPriority) :改变线程的优先级 */class SubThread1 extends Thread {    public void run() {        for (int i = 1; i <= 100; i++) {            // try {            // Thread.currentThread().sleep(1000);            // } catch (InterruptedException e) {            // // TODO Auto-generated catch block            // e.printStackTrace();            // }            System.out.println(Thread.currentThread().getName() + ":"                    + Thread.currentThread().getPriority() + ":" + i);        }    }}public class TestThread1 {    public static void main(String[] args) {        SubThread1 st1 = new SubThread1();        st1.setName("子线程1");        st1.setPriority(Thread.MAX_PRIORITY);        st1.start();        Thread.currentThread().setName("========主线程");        for (int i = 1; i <= 100; i++) {            System.out.println(Thread.currentThread().getName() + ":"                    + Thread.currentThread().getPriority() + ":" + i);            // if(i % 10 == 0){            // Thread.currentThread().yield();            // }            // if(i == 20){            // try {            // st1.join();            // } catch (InterruptedException e) {            // // TODO Auto-generated catch block            // e.printStackTrace();            // }            // }        }        System.out.println(st1.isAlive());    }}

线程的开启过程:
这里写图片描述

2.如何创建java程序的线程(重点)

方式一:继承于Thread类

class PrintNum extends Thread{    public void run(){        //子线程执行的代码        for(int i = 1;i <= 100;i++){            if(i % 2 == 0){                System.out.println(Thread.currentThread().getName() + ":" + i);            }        }    }    public PrintNum(String name){        super(name);    }}public class TestThread {    public static void main(String[] args) {        PrintNum p1 = new PrintNum("线程1");        PrintNum p2 = new PrintNum("线程2");        p1.setPriority(Thread.MAX_PRIORITY);//10        p2.setPriority(Thread.MIN_PRIORITY);//1        p1.start();        p2.start();    }}

方式二:实现Runnable接口

class SubThread implements Runnable{    public void run(){        //子线程执行的代码        for(int i = 1;i <= 100;i++){            if(i % 2 == 0){                System.out.println(Thread.currentThread().getName() + ":" + i);            }        }               }}public class TestThread{    public static void main(String[] args){        SubThread s = new SubThread();        Thread t1 = new Thread(s);        Thread t2 = new Thread(s);        t1.setName("线程1");        t2.setName("线程2");        t1.start();        t2.start();    }}

两种方式的对比:
哪个比较好?实现的方式较好。class Thread implements Runnable
①解决了单继承的局限性。②如果多个线程有共享数据的话,建议使用实现方式,同时,共享数据所在的类可以作为Runnable接口的实现类。

联系:
这里写图片描述

继承的方式其实也是实现的Runnable接口。

线程里的常用方法:

start() run() currentThread() getName() setName(String name) yield() join() sleep() isAlive() getPriority() setPriority(int i); wait() notify() notifyAll()

补充:线程的分类
Java中的线程分为两类:一种是守护线程,一种是用户线程。

  • 它们在几乎每个方面都是相同的,唯一的区别是判断JVM何时离开。
  • 守护线程是用来服务用户线程的,通过在start()方法前调用thread.setDaemon(true)可以把一个用户线程变成一个守护线程。
  • Java垃圾回收就是一个典型的守护线程。
  • 若JVM中都是守护线程,当前JVM将退出。

3.线程的生命周期

这里写图片描述

4.线程的同步机制(重点、难点)

前提:如果我们创建的多个线程,存在着共享数据,那么就有可能出现线程的安全问题:当其中一个线程操作共享数据时,还未操作完成,另外的线程就参与进来,导致对共享数据的操作出现问题。
解决方式:要求一个线程操作共享数据时,只有当其完成操作完成共享数据,其它线程才有机会执行共享数据。

方式一:
同步代码块:
synchronized(同步监视器){
//操作共享数据的代码
}

注:1.同步监视器:俗称锁,任何一个类的对象都可以才充当锁。要想保证线程的安全,必须要求所有的线程共用同一把锁!
2.使用实现Runnable接口的方式创建多线程的话,同步代码块中的锁,可以考虑是this。如果使用继承Thread类的方式,慎用this!
3.共享数据:多个线程需要共同操作的变量。 明确哪部分是操作共享数据的代码。

方式二:
同步方法:将操作共享数据的方法声明为synchronized。
比如:public synchronized void show(){ //操作共享数据的代码}

注:1.对于非静态的方法而言,使用同步的话,默认锁为:this。如果使用在继承的方式实现多线程的话,慎用!
2.对于静态的方法,如果使用同步,默认的锁为:当前类本身。以单例的懒汉式为例。 Class clazz = Singleton.class

总结: 释放锁:wait();
不释放锁: sleep() yield() suspend() (过时,可能导致死锁)

1.同步机制例题:售票

//使用实现Runnable接口的方式,售票/* * 此程序存在线程的安全问题:打印车票时,会出现重票、错票 * 1.线程安全问题存在的原因? *   由于一个线程在操作共享数据过程中,未执行完毕的情况下,另外的线程参与进来,导致共享数据存在了安全问题。 *    * 2.如何来解决线程的安全问题? *   必须让一个线程操作共享数据完毕以后,其它线程才有机会参与共享数据的操作。 *  * 3.java如何实现线程的安全:线程的同步机制 *       *      方式一:同步代码块 *      synchronized(同步监视器){ *          //需要被同步的代码块(即为操作共享数据的代码) *      } *      1.共享数据:多个线程共同操作的同一个数据(变量) *      2.同步监视器:由一个类的对象来充当。哪个线程获取此监视器,谁就执行大括号里被同步的代码。俗称:锁 *      要求:所有的线程必须共用同一把锁! *      注:在实现的方式中,考虑同步的话,可以使用this来充当锁。但是在继承的方式中,慎用this! *  *      方式二:同步方法 *      将操作共享数据的方法声明为synchronized。即此方法为同步方法,能够保证当其中一个线程执行 *      此方法时,其它线程在外等待直至此线程执行完此方法。 *      >同步方法的锁:this *  * 4.线程的同步的弊端:由于同一个时间只能有一个线程访问共享数据,效率变低了。 *  */class Window4 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) {                // TODO Auto-generated catch block                e.printStackTrace();            }            System.out.println(Thread.currentThread().getName() + "售票,票号为:"                    + ticket--);        }    }}public class TestWindow4 {    public static void main(String[] args) {        Window4 w = new Window4();        Thread t1 = new Thread(w);        Thread t2 = new Thread(w);        Thread t3 = new Thread(w);        t1.setName("窗口1");        t2.setName("窗口2");        t3.setName("窗口3");        t1.start();        t2.start();        t3.start();    }}

2.懒汉式改进(加入同步机制)

//关于懒汉式的线程安全问题:使用同步机制//对于一般的方法内,使用同步代码块,可以考虑使用this。//对于静态方法而言,使用当前类本身充当锁。class Singleton {    private Singleton() {    }    private static Singleton instance = null;    public static Singleton getInstance() {        if (instance == null) {            synchronized (Singleton.class) {                if (instance == null) {                    instance = new Singleton();                }            }        }        return instance;    }}public class TestSingleton {    public static void main(String[] args) {        Singleton s1 = Singleton.getInstance();        Singleton s2 = Singleton.getInstance();        System.out.println(s1 == s2);        // Class clazz = Singleton.class;    }}

死锁:
不同的线程分别占用对方需要的同步资源不放弃,都在等待对方放弃自己需要的同步资源,就形成了线程的死锁
死锁是我们在使用同步时,需要避免的问题!

1.死锁的简单例子:

//死锁的问题:处理线程同步时容易出现。//不同的线程分别占用对方需要的同步资源不放弃,都在等待对方放弃自己需要的同步资源,就形成了线程的死锁//写代码时,要避免死锁!public class TestDeadLock {    static StringBuffer sb1 = new StringBuffer();    static StringBuffer sb2 = new StringBuffer();    public static void main(String[] args) {        new Thread() {            public void run() {                synchronized (sb1) {                    try {                        Thread.currentThread().sleep(10);                    } catch (InterruptedException e) {                        // TODO Auto-generated catch block                        e.printStackTrace();                    }                    sb1.append("A");                    synchronized (sb2) {                        sb2.append("B");                        System.out.println(sb1);                        System.out.println(sb2);                    }                }            }        }.start();        new Thread() {            public void run() {                synchronized (sb2) {                    try {                        Thread.currentThread().sleep(10);                    } catch (InterruptedException e) {                        // TODO Auto-generated catch block                        e.printStackTrace();                    }                    sb1.append("C");                    synchronized (sb1) {                        sb2.append("D");                        System.out.println(sb1);                        System.out.println(sb2);                    }                }            }        }.start();    }}

5.线程的通信

wait() 与 notify() 和 notifyAll()

  • wait():令当前线程挂起并放弃CPU、同步资源,使别的线程可访问并修改共享资源,而当前线程排队等候再次对资源的访问
  • notify():唤醒正在排队等待同步资源的线程中优先级最高者结束等待
  • notifyAll ():唤醒正在排队等待资源的所有线程结束等待.

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

如下的三个方法必须使用在同步代码块或同步方法中!
wait():当在同步中,执行到此方法,则此线程“等待”,直至其他线程执行notify()的方法,将其唤醒,唤醒后继续其wait()后的代码
notify()/notifyAll():在同步中,执行到此方法,则唤醒其他的某一个或所有的被wait的线程。

例题:1.两个线程交替打印1-100自然数 2.生产者、消费者的例子

两个线程交替打印1-100自然数

//线程通信。如下的三个关键字使用的话,都得在同步代码块或同步方法中。//wait():一旦一个线程执行到wait(),就释放当前的锁。//notify()/notifyAll():唤醒wait的一个或所有的线程//使用两个线程打印 1-100. 线程1, 线程2 交替打印class PrintNum implements Runnable {    int num = 1;    Object obj = new Object();    public void run() {        while (true) {            synchronized (obj) {                obj.notify();                if (num <= 100) {                    try {                        Thread.currentThread().sleep(10);                    } catch (InterruptedException e) {                        // TODO Auto-generated catch block                        e.printStackTrace();                    }                    System.out.println(Thread.currentThread().getName() + ":"                            + num);                    num++;                } else {                    break;                }                try {                    obj.wait();                } catch (InterruptedException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        }    }}public class TestCommunication {    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();    }}

生产者、消费者问题:

/* * 生产者/消费者问题 * 生产者(Productor)将产品交给店员(Clerk),而消费者(Customer)从店员处取走产品, * 店员一次只能持有固定数量的产品(比如:20),如果生产者试图生产更多的产品,店员会叫生产者停一下, * 如果店中有空位放产品了再通知生产者继续生产;如果店中没有产品了,店员会告诉消费者等一下, * 如果店中有产品了再通知消费者来取走产品。    分析:    1.是否涉及到多线程的问题?是!生产者、消费者    2.是否涉及到共享数据?有!考虑线程的安全    3.此共享数据是谁?即为产品的数量    4.是否涉及到线程的通信呢?存在这生产者与消费者的通信 */class Clerk{//店员    int product;    public synchronized void addProduct(){//生产产品        if(product >= 20){            try {                wait();            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }else{            product++;            System.out.println(Thread.currentThread().getName() + ":生产了第" + product + "个产品");            notifyAll();        }    }    public synchronized void consumeProduct(){//消费产品        if(product <= 0){            try {                wait();            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }else{            System.out.println(Thread.currentThread().getName() + ":消费了第" + product + "个产品");            product--;            notifyAll();        }    }}class Producer implements Runnable{//生产者    Clerk clerk;    public Producer(Clerk clerk){        this.clerk = clerk;    }    public void run(){        System.out.println("生产者开始生产产品");        while(true){            try {                Thread.currentThread().sleep(100);            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            clerk.addProduct();        }    }}class Consumer implements Runnable{//消费者    Clerk clerk;    public Consumer(Clerk clerk){        this.clerk = clerk;    }    public void run(){        System.out.println("消费者消费产品");        while(true){            try {                Thread.currentThread().sleep(10);            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            clerk.consumeProduct();        }    }}public class TestProduceConsume {    public static void main(String[] args) {        Clerk clerk = new Clerk();        Producer p1 = new Producer(clerk);        Consumer c1 = new Consumer(clerk);        Thread t1 = new Thread(p1);//一个生产者的线程        Thread t3 = new Thread(p1);        Thread t2 = new Thread(c1);//一个消费者的线程        t1.setName("生产者1");        t2.setName("消费者1");        t3.setName("生产者2");        t1.start();        t2.start();        t3.start();    }}
0 0
原创粉丝点击