最终版:
测试类:
- package com.kxg_03;
- public class StudentDemo {
- public static void main(String[] args) {
- // 创建资源
- Student s = new Student();
- // 创建SetThread和GetThread对象
- SetThread st = new SetThread(s);
- GetThread gt = new GetThread(s);
- // 创建线程
- Thread t1 = new Thread(st);
- Thread t2 = new Thread(gt);
- // 开启线程
- t1.start();
- t2.start();
- }
- }
复制代码 资源类:
- package com.kxg_03;
- /*
- * 定义学生类
- */
- public class Student {
- String name;
- int age;
- boolean flag;// 用来判断是否存在资源,默认是flash,没有资源
- public synchronized void set(String name, int age) {
- // 生产者,如果有数据就等待
- if (!this.flag) {
- try {
- this.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- // 设置数据
- this.name = name;
- this.age = age;
- // 修改标记
- this.flag = false;
- // 唤醒线程
- this.notify();
- }
- public synchronized void get() {
- if (this.flag) {
- try {
- this.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- System.out.println(this.name + ":" + this.age);
- // 修改标记
- this.flag = true;
- // 唤醒线程
- this.notify();
- }
- }
复制代码 设置类:- package com.kxg_03;
- /*
- * 设置学生信息的线程
- */
- public class SetThread implements Runnable {
- private Student s;
- private int i;
- public SetThread(Student s) {
- this.s = s;
- }
- @Override
- public void run() {
- while (true) {
- if (i % 2 == 0) {
- s.set("小明", 5);
- } else {
- s.set("汪汪", 2);
- }
- i++;
- }
- }
- }
复制代码 获取类:
- package com.kxg_03;
- /*
- * 设置获取学生信息的线程
- */
- public class GetThread implements Runnable {
- private Student s;
- public GetThread(Student s) {
- this.s = s;
- }
- @Override
- public void run() {
- while (true) {
- s.get();
- }
- }
- }
复制代码
|