当前位置: 移动技术网 > IT编程>开发语言>Java > Java多线程

Java多线程

2019年04月08日  | 移动技术网IT编程  | 我要评论

什么是多线程

利用对象,可将一个程序分割成相互独立的区域。我们通常也需要将一个程序转换成多个独立运行的子任
务。象这样的每个子任务都叫作一个“线程”(thread)。编写程序时,可将每个线程都想象成独立运行,而且
都有自己的专用cpu。一些基础机制实际会为我们自动分割cpu的时间。我们通常不必关心这些细节问题,
所以多线程的代码编写是相当简便的。引自《java编程思想》第四版

生命周期

在这里插入图片描述

如何开启一个线程

  • 继承thread

thread类本质上是实现了runnable接口的一个实例,代表一个线程的实例。启动线程的唯一方法就是通过thread类的start()实例方法。start()方法是一个native方法,它将启动一个新线程,并执行run()方法。这种方式实现多线程很简单,通过自己的类直接extend thread,并复写run()方法,就可以启动新线程并执行自己定义的run()方法。例如:

public class startthread extends thread {

    @override
    public void run() {
        for (int i = 0; i < 120; i++) {
            system.out.println("听歌。。。");
        }
    }

    public static void main(string[] args) {
        startthread st = new startthread();
        st.start();
        for (int i = 0; i < 120; i++) {
            system.out.println("敲代码。。。");
        }
    }
}
  • 实现runnable接口

如果自己的类已经extends另一个类,就无法直接extends thread,此时,可以实现一个runnable接口,如下:

public class startrunnable implements runnable {
    @override
    public void run() {
        for (int i = 0; i < 120; i++) {
            system.out.println("听歌。。。");
        }
    }

    public static void main(string[] args) {
        startrunnable sr = new startrunnable();
        thread t = new thread(sr);
        t.start();
        for (int i = 0; i < 120; i++) {
            system.out.println("敲代码。。。");
        }
    }
}
  • 实现callable接口

实现callable接口实现线程开启相比较上两个步骤会多一些,是juc并发包下的一个接口。

public class startcallable implements callable<integer> {

    @override
    public integer call() throws exception {
        for (int i = 0; i < 120; i++) {
            system.out.println("听歌。。。");
        }
        return 1;
    }
    public static void main(string[] args) throws exception {
        startcallable sc = new startcallable();
        executorservice es = executors.newfixedthreadpool(1);
        future<integer> submit = es.submit(sc);
        integer result = submit.get();
        es.shutdownnow();
        system.out.println(result);
        for (int i = 0; i < 120; i++) {
            system.out.println("敲代码。。。");
        }
    }
}

线程状态

线程在生命周期内,共五大状态
在这里插入图片描述
具体说明:

  • 实例线程--->新生状态
  • 调用start()--->就绪状态
  • 操作系统cpu调度器分配好进行调用--->运行状态
  • 线程正常执行完毕或外部干涉--->死亡状态
  • io文件读写、调用sleep()、调用wait()--->阻塞状态
    在这里插入图片描述
    线程主要方法:
    在这里插入图片描述

    线程终止

停止线程的stop()方法jdk已经过失,不推荐使用,如何优雅的停止线程呢?举例:

public class study implements runnable {
    // 线程类中,定义线程体使用的标识
    private boolean stop = true;

    private string name;

    study(string name) {
        this.name = name;
    }

    @override
    public void run() {
        int i = 0;
        // 线程体使用该标识
        while (stop) {
            system.out.println(name + "线程正常运行。。。===>" + i++);
        }
    }
    // 对外提供方法改变标识
    public void stop() {
        this.stop = false;
    }

    public static void main(string[] args) {
        study s = new study("张三");
        thread thread = new thread(s);
        thread.start();
        for (int i = 0; i < 1000; i++) {
            if (i == 900) {
                s.stop();
                system.out.println("game over。。。。。。");
            }
            system.out.println("main====>" + i);
        }
    }
}

暂停 sleep()

  • sleep(时间)指定当前线程阻塞的毫秒数
  • sleep()存在异常 interruptedexcetion
  • sleep()时间到达后线程进入就绪状态
  • sleep()可以模拟网络延时、倒计时等
  • 每一个对象都有一个锁,sleep()不会释放锁
  • 举例:
// sleep() 模拟倒计时
public static void main(string[] args) throws interruptedexception {
    // 当前时间戳
    long millis = system.currenttimemillis();
    // 当前时间加十秒
    date endtime = new date(millis + 1000 * 10);
    long end = endtime.gettime();
    simpledateformat sdf = new simpledateformat("yyyy-mm-dd hh:mm:ss");
    for (; ; ) {
        system.out.println(sdf.format(endtime));
        // 睡眠一秒
        thread.sleep(1000l);
        // 获取倒计时一秒后的时间
        endtime = new date(endtime.gettime() - 1000l);
        if ((end - 10000) >= endtime.gettime()) {
            break;
        }
    }
}

yield()

  • 礼让线程,让当前正在执行的线程暂停
  • 不是阻塞线程,而是将线程从 运行状态 转入就绪状态
  • 让cpu调度器重新调度

举例:

public class yield {
    public static void main(string[] args) {
        new thread(()-> {
            for (int i = 0; i < 100; i++) {
                system.out.println("我是另一个线程。。。");
            }
        }).start();
        for (int i = 0; i < 100; i++) {
            if (i % 20 == 0) {
                system.out.println(i + "-->开始礼让");
                // main线程进行礼让
                thread.yield();
            }
            system.out.println("main 线程-->" + i);
        }
    }
}

注意:yield是让线程进入就绪状态,不是阻塞状态。

插队 join()

join() 合并线程,待此线程执行完毕后,再执行其他线程,其他线程阻塞

举例:

public class example {
    public static void main(string[] args) {
        system.out.println("买烟的故事。。。");
        new thread(new father()).start();
    }
}

class father extends thread {
    @override
    public void run() {
        system.out.println("老爸抽烟,烟没了,让儿子买烟。");
        thread t = new thread(new son());
        t.start();
        try {
            // father 线程被阻塞
            t.join();
            system.out.println("儿子把烟买来了,交给老爸,老爸把剩余零钱给了儿子。");
        } catch (interruptedexception e) {
            system.out.println("儿子走丢了。。。");
        }
    }
}

class son extends thread {
    @override
    public void run() {
        system.out.println("接过老爸的钱去买烟");
        system.out.println("路边有个游戏厅,玩了10秒");
        for (int i = 0; i < 10; i++) {
            system.out.println(i + "秒过去了。。。");
            try {
                thread.sleep(1000l);
            } catch (interruptedexception e) {
                e.printstacktrace();
            }
        }
        system.out.println("突然想起还要买烟,赶紧买烟。");
        system.out.println("手拿一包中华,回家了。");
    }
}

深度观察状态

/**
 * 观察线程状态
 */
public class allstate {
    public static void main(string[] args) throws interruptedexception {
        thread t = new thread(()-> {
            for (int i = 0; i < 10; i++) {
                try {
                    thread.sleep(100l);
                } catch (interruptedexception e) {
                    e.printstacktrace();
                }
                system.out.println("....");
            }
        });
        // 观察状态
        thread.state state = t.getstate();
        // 新创建处理新生状态,state为new
        system.out.println(state.tostring());
        t.start();
        state = t.getstate();
        // 线程就绪,就绪状态到运行状态是cpu控制的,所以一般调用了线程的 start()方法后,
        // state为runnable
        system.out.println(state.tostring());

        for (; state != thread.state.terminated;) {
            thread.sleep(200l);
            // 线程阻塞 state为timed_waiting
            state = t.getstate();
            system.out.println(state.tostring());
        }
        // 线程运行结束 state为terminated
        state = t.getstate();
        system.out.println(state.tostring());
    }
}

线程优先级

在多个线程同时执行的时候,线程调度器会根据优先级,优先调用级别高的线程。(只是决定优先调用,不代表先后顺序。)

  • max_priority(10,线程可以拥有的最大优先级)
  • min_priority(1,线程可以拥有的最小优先级)
  • norm_priority(5,分配给线程的默认优先级)

举例:

public class prioritytest {
    public static void main(string[] args) {
        testpriority tp = new testpriority();
        thread t = new thread(tp);
        t.setpriority(thread.max_priority);
        t.start();
        thread t1 = new thread(tp);
        t1.setpriority(thread.max_priority);
        t1.start();
        thread t2 = new thread(tp);
        t2.setpriority(thread.max_priority);
        t2.start();
        thread t3 = new thread(tp);
        t3.setpriority(thread.min_priority);
        t3.start();
        thread t4 = new thread(tp);
        t4.setpriority(thread.min_priority);
        t4.start();
        thread t5 = new thread(tp);
        t5.setpriority(thread.min_priority);
        t5.start();
    }
}

class testpriority implements runnable {
    @override
    public void run() {
        thread thread = thread.currentthread();
        string threadname = thread.getname();
        int threadpriority = thread.getpriority();
        system.out.println(threadname + "--->" + threadpriority);
        thread.yield();
    }
}

如果优先级高的话,那么先执行的概率会大一些,但不是绝对。

守护线程

守护线程是为用户线程服务的,jvm停止不用等待守护线程执行完毕。

  • 线程分为用户线程和守护线程
  • 虚拟机必须确保用户线程执行完毕
  • 虚拟机不用等待守护线程执行完毕
  • 如后台记录操作日志、监控内存使用等

默认情况下,线程都是用户线程,虚拟机等待所有用户线程执行完毕才会停止。

public class daemontest {
    public static void main(string[] args) {
        god god = new god();
        you you = new you();
        thread t = new thread(god);
        // 将用户线程调整为守护线程(默认为false)
        t.setdaemon(true);
        t.start();
        new thread(you).start();
        // god调整为守护线程时,当you线程结束后,god也随即结束。
    }
}
// 我
class you implements runnable {
    @override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            system.out.println("幸福的生活着。。。");
        }
        system.out.println("game over!");
    }
}
// 上帝
class god implements runnable {
    @override
    public void run() {
        for (; ;) {
            system.out.println("上帝守护你。。。");
        }
    }
}

其它常用方法

  • isalive(),判断当前线程是否活着,即线程是否还未终止
  • setname(),给当前线程赋名字
  • getname(),获取当前线程名字
  • currentthread(),取得当前运行的线程对象,或者说是获取自己本身

举例 :

public class othermethod {
    public static void main(string[] args) throws exception {
        thread thread = thread.currentthread();
        system.out.println(thread);
        system.out.println(thread.isalive());
        system.out.println(thread.getname());

        myinfo myinfo = new myinfo("张三");
        thread t = new thread(myinfo);
        t.setname("李四");
        t.start();
        thread.sleep(2000l);
        system.out.println(t.isalive());
    }
}

class myinfo implements runnable {
    private string name;
    myinfo(string name) {
        this.name = name;
    }
    @override
    public void run() {
        system.out.println(thread.currentthread().getname() + "--->" + name);
    }
}

线程同步

讲到线程同步就要理解什么是并发了,并发就是同一个对象同时被多个线程访问。一旦出现并发就会线程不安全最终就可能导致数据结果不准确等一些问题。

线程同步本质就是一种等待机制,多个需要同时访问此对象的线程进入这个对象的 等待池形成队列 ,等待前面的线程使用完毕后,先一个线程再使用。

如何保证线程安全:

队列形式,排队执行,通过锁的方式,标志某个线程正在占用某个资源,处理完毕后释放锁让队列中其它线程继续执行。
在这里插入图片描述

synchronized

synchronized 关键字包括两种用法,synchronized 方法 和 synchronized 代码块

synchronized 方法控制对“成员变量|类变量”对象的访问,每个对象对应一把锁,每个 synchronized 方法都必须获得调用该方法的对象的锁才能执行,否则所属线程阻塞,方法一旦执行,就独占该锁,直到从该方法返回时才将锁释放,此后被阻塞的线程方能获得该锁,重新进入可执行状态。

synchronized方法
/**
 * 模拟抢票
 * 保证线程安全,并发时保证数据的正确性、效率尽可能高
 */
public class syncweb12306 implements runnable {
    // 票数
    private int ticketnums = 10;
    private boolean flag = true;
    @override
    public void run() {
        for (; ; ) {
            if (!flag) {
                break;
            }
            test();
        }
    }
    // 使用 synchronized 关键字 锁住资源(this)
    public synchronized void test() {
        if (ticketnums <= 0) {
            this.flag = false;
            return;
        }
        try {
            thread.sleep(200l);
        } catch (interruptedexception e) {
            e.printstacktrace();
        }
        system.out.println(thread.currentthread().getname() + "--->" + ticketnums--);
    }
    public static void main(string[] args) {
        // 一份资源
        syncweb12306 web = new syncweb12306();
        // 多个线程同时访问
        new thread(web, "张三").start();
        new thread(web, "李四").start();
        new thread(web, "王五").start();
    }
}
synchronized代码块
/**
 * 模拟并发操作取钱
 */
public class syncdrawmoney {
    int money;  // 金额
    string name;    // 名称
    syncdrawmoney(int money, string name) {
        this.money = money;
        this.name = name;
    }
    public static void main(string[] args) {
        syncdrawmoney drawmoney = new syncdrawmoney(100, "买车");
        syncdrawing you = new syncdrawing(drawmoney, 100, "张三");
        syncdrawing wife = new syncdrawing(drawmoney, 100, "张三老婆");
        you.start();
        wife.start();
    }
}

// 模拟取款
class syncdrawing extends thread {
    syncdrawmoney drawmoney;    // 取钱账户
    int drawingmoney;   // 取的钱数
    int packettotal;   // 口袋里的钱
    public syncdrawing(syncdrawmoney drawmoney, int drawingmoney, string name) {
        super(name);
        this.drawmoney = drawmoney;
        this.drawingmoney = drawingmoney;
    }

    @override
    public void run() {
        test();
    }

    private void test() {
        if (drawmoney.money > 0) {
            // 锁住具体要操作的对象
            synchronized (drawmoney) {
                if (drawmoney.money < drawingmoney) {
                    system.out.println(thread.currentthread().getname() + "取" + drawingmoney + "但是,余额还有" + drawmoney.money);
                    system.out.println("钱不够了。。。");
                    return;
                }
                if (drawmoney.money - drawingmoney < 0) {
                    system.out.println(thread.currentthread().getname() + "取" + drawingmoney + "但是,余额还有" + drawmoney.money);
                    system.out.println("没钱了。。。");
                    return;
                }
                try {
                    thread.sleep(1000l);
                } catch (interruptedexception e) {
                    e.printstacktrace();
                }
                drawmoney.money -= drawingmoney;
                packettotal += drawingmoney;
                system.out.println(thread.currentthread().getname() + "--->账户余额为:" + drawmoney.money);
                system.out.println(thread.currentthread().getname() + "--->口袋钱为:" + packettotal);
            }
        } else {
            system.out.println("账户没钱了。。。");
        }
    }
}

性能分析

public class propertyweb12306 implements runnable {

    // 票数
    private integer ticketnums = 10;

    private boolean flag = true;

    @override
    public void run() {
        for (; ; ) {
            if (!flag) {
                break;
            }
            test3();
        }
    }

    // 尽可能锁定合理范围(合理范围不是指代码,指的是数据的完整性)
    void test3() {
        if (ticketnums <= 0) {
            this.flag = false;
            return;
        }
        synchronized (this) {
            if (ticketnums <= 0) {
                this.flag = false;
                return;
            }
            try {
                thread.sleep(200l);
            } catch (interruptedexception e) {
                e.printstacktrace();
            }
            system.out.println(thread.currentthread().getname() + "--->" + ticketnums--);
        }
    }

    // 同步代码块范围小,锁不住,导致线程不安全
    void test2() {
        synchronized (this) {
            if (ticketnums <= 0) {
                this.flag = false;
                return;
            }
        }
        try {
            thread.sleep(200l);
        } catch (interruptedexception e) {
            e.printstacktrace();
        }
        system.out.println(thread.currentthread().getname() + "--->" + ticketnums--);
    }

    // 同步代码块,锁住当前对象,范围大,虽然实现了线程安全,但是性能低下。
    void test1() {
        synchronized (this) {
            if (ticketnums <= 0) {
                this.flag = false;
                return;
            }
            try {
                thread.sleep(200l);
            } catch (interruptedexception e) {
                e.printstacktrace();
            }
            system.out.println(thread.currentthread().getname() + "--->" + ticketnums--);
        }
    }

    // 线程安全,同步
    synchronized void test() {
        if (ticketnums <= 0) {
            this.flag = false;
            return;
        }
        try {
            thread.sleep(200l);
        } catch (interruptedexception e) {
            e.printstacktrace();
        }
        system.out.println(thread.currentthread().getname() + "--->" + ticketnums--);
    }

    public static void main(string[] args) {
        // 一份资源
        propertyweb12306 web = new propertyweb12306();
        // 多个线程同时访问
        new thread(web, "张三").start();
        new thread(web, "李四").start();
        new thread(web, "王五").start();
    }
}

注意:实际开发中,尽量多用同步代码块,少用同步方法

线程同步小案例

购买电影票小案例

/**
 * 快乐影院
 */
public class happycinema {
    public static void main(string[] args) {
        // 可用位置
        list<integer> available = new arraylist<>();
        available.add(1);
        available.add(2);
        available.add(4);
        available.add(6);
        available.add(5);
        available.add(7);
        available.add(3);
        // 影院
        cinema c = new cinema(available, "夜上海影院");
        // 来两个顾客
        list<integer> seats01 = new arraylist<>();
        seats01.add(1);
        seats01.add(2);
        seats01.add(4);
        new thread(new customer(c, seats01), "张三").start();

        list<integer> seats02 = new arraylist<>();
        seats02.add(4);
        seats02.add(6);
        seats02.add(7);
        new thread(new customer(c, seats02), "李四").start();
    }
}

/**
 * 顾客
 */
class customer implements runnable {
    // 电影院
    cinema cinema;
    // 需要几个位置
    list<integer> seats;
    customer(cinema cinema, list<integer> seats) {
        this.cinema = cinema;
        this.seats = seats;
    }
    @override
    public void run() {
        thread thread = thread.currentthread();
        synchronized (cinema) {
            boolean flag = cinema.booktickets(this.seats);
            if (flag) {
                system.out.println(thread.getname() + "-->购票成功。。。" + "位置为:" + this.seats);
            } else {
                system.out.println(thread.getname() + "-->购票失败***" + "位置不够");
            }
        }
    }
}

/**
 * 影院
 */
class cinema {
    list<integer> available;  // 可用位置
    string name;    // 名称
    cinema(list<integer> available, string name) {
        this.available = available;
        this.name = name;
    }
    // 购票
    boolean booktickets(list<integer> seats) {
        system.out.println("欢迎光临【" + this.name + "】当前可用的位置为" + available);
        system.out.println(thread.currentthread().getname() + "-->想要购买" + seats);
        list<integer> copy = new arraylist<>(available);
        // 相减
        copy.removeall(seats);
        // 判断大小
        if (seats.size() != (available.size() - copy.size())) {
            return false;
        }
        available = copy;
        return true;
    }
}

购买火车票小案例

/**
 * 购买火车票  线程安全版
 */
public class happy12306 {
    public static void main(string[] args) {
        web12306 web = new web12306(4, "杭州");
        new passenger(web, "张三", 2).start();
        new passenger(web, "李四", 1).start();
    }
}

// 乘客
class passenger extends thread {
    int seats;
    public passenger(runnable target, string name, int seats) {
        super(target, name);
        this.seats = seats;
    }
}

// 火车票网站
class web12306 implements runnable {
    int available;  // 可用位置
    string name;    // 名称

    public web12306(int available, string name) {
        this.available = available;
        this.name = name;
    }

    @override
    public void run() {
        passenger p = (passenger) thread.currentthread();
        boolean flag = this.booktickets(p.seats);
        if (flag) {
            system.out.println("出票成功" + p.getname() + "位置为:" + p.seats);
        } else {
            system.out.println("出票失败" + p.getname() + "位置不够");
        }
    }

    // 购票
    synchronized boolean booktickets(int seats) {
        system.out.println("可用位置为:" + this.available);
        if (seats > this.available) {
            return false;
        }
        available -= seats;
        return true;
    }
}

死锁

多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能进行,而导致两个或者多个线程都在等待对方释放资源,都停止执行的情形。某一个同步块同时拥有“两个以上对象的锁”时,就可能会发生“死锁”的问题。

通俗一些就是:你给钱,我给货。我想让你先给货,你想让我先给钱,一直僵持着。

过多的同步有可能会造成死锁

如何避免:

不要再同步一个代码块同时持有多个对象的锁

并发协作

生产者消费者模式

本质是一个线程同步问题,生产者和消费者共享同一个资源,并且生产者和消费者之间相互依赖,互为条件。

  • 对于生产者而言,没有生产产品之前,要通知消费者等待。而生产了之后,需要马上通知消费者
  • 对于消费者而言,在消费之后,要通知生产者已经消费结束,需要继续生产新产品以供消费
  • 在生产者消费者问题中,仅有 synchronized 时不够的,还需要等待和通知等操作
    • synchronized 可阻止并发更新同一个共享资源,实现同步
    • synchronized 不能用来实现不同线程之间的消息传递(通信)
      在这里插入图片描述
      java提供了3个方法解决线程之间的通信问题
方法名 作用
final void wait() 表示线程一直等待,直到其他线程通知,与sleep()不同,会释放锁
final void wait(long timeout) 指定等待的毫秒数
final void notifiy() 唤醒一个处于等待状态的线程
final void notifiyall() 唤醒同一个对象上所有调用wait()方法的线程,优先级别高的线程优先调度

注意:以上方法都只能在同步方法或者同步代码块中使用,否则会抛出异常

实现方式一:管程法
在这里插入图片描述

/**
 * 协作模型:
 * 生产者消费者模式方式一:管程法
 */
public class cotest01 {
    public static void main(string[] args) {
        synccontainer container = new synccontainer();
        // 生产者
        new productor(container).start();
        // 消费者
        new consumer(container).start();
    }
}
// 生产者
class productor extends thread {
    synccontainer container;

    public productor(synccontainer container) {
        this.container = container;
    }

    @override
    public void run() {
        // 开始生产
        for (int i = 0; i < 100; i++) {
            system.out.println("生产第" + i + "个馒头。。。");
            container.push(new steamedbun(i));
        }
    }
}

// 消费者
class consumer extends thread {
    synccontainer container;

    public consumer(synccontainer container) {
        this.container = container;
    }
    @override
    public void run() {
        // 开始消费
        for (int i = 0; i < 100; i++) {
            system.out.println("消费第" + container.pop().id + "个馒头。。。");
        }
    }
}

// 缓冲区
class synccontainer {
    steamedbun[] steamedbuns = new steamedbun[10];  // 存储容器
    int count = 0;  // 计数器

    // 存储  生产
    synchronized void push(steamedbun steamedbun) {
        // 不能生产
        if (count == steamedbuns.length) {
            try {
                this.wait();    // 线程阻塞 消费者通知生产解除
            } catch (interruptedexception e) {
                e.printstacktrace();
            }
        }
        steamedbuns[count] =steamedbun;
        count++;
        // 存在数据了,可以通知消费
        this.notifyall();
    }

    // 获取 消费
    synchronized steamedbun pop() {
        if (count == 0) {
            try {
                this.wait();    // 线程阻塞 生产者通知消费,解除阻塞
            } catch (interruptedexception e) {
                e.printstacktrace();
            }
        }
        count--;
        this.notifyall();   // 存在空间 唤醒所有
        return steamedbuns[count];
    }
}

// 数据,举例为馒头
class steamedbun {
    int id;

    public steamedbun(int id) {
        this.id = id;
    }
}

实现方式二:信号灯法
在这里插入图片描述

/**
 * 协作模型:
 * 生产者消费者模式方式一:信号灯法
 * 借助标注位
 */
public class cotest02 {
    public static void main(string[] args) {
        tv tv = new tv();
        new player(tv).start();
        new watcher(tv).start();
    }
}
// 生产者 演员
class player extends thread {
    tv tv;

    public player(tv tv) {
        this.tv = tv;
    }

    @override
    public void run() {
        for (int i = 0; i < 20; i++) {
            if ((i % 2) == 0) {
                this.tv.play("奇葩说。。。");
            } else {
                this.tv.play("直播广告。。。");
            }
        }
    }
}
// 消费者观众
class watcher extends thread {
    tv tv;

    public watcher(tv tv) {
        this.tv = tv;
    }

    @override
    public void run() {
        for (int i = 0; i < 20; i++) {
            tv.watch();
        }
    }
}

// 同一个资源 电视
class tv {
    string voice;
    boolean flag = true; // 信号灯,如果为 true 演员表演观众观看,否则观众观看演员等待

    // 表演
    synchronized void play(string voice) {
        // 演员等待
        if (!flag) {
            try {
                this.wait();
            } catch (interruptedexception e) {
                e.printstacktrace();
            }
        }
        this.voice = voice;
        // 表演
        system.out.println("表演了:" + this.voice);
        this.notifyall();   // 唤醒
        this.flag = !this.flag;
    }
    // 观看
    synchronized void watch() {
        // 观众等待
        if (flag) {
            try {
                this.wait();
            } catch (interruptedexception e) {
                e.printstacktrace();
            }
        }
        // 观看
        system.out.println("听到了:" + this.voice);
        this.notifyall();   // 唤醒
        this.flag = !this.flag;
    }
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网