「已注销」 2016-03-02 14:35 采纳率: 50%
浏览 2465
已采纳

多线程中this关键字的问题

 package wintervacation.multithreading;

/**
 * Created by wangw on 2016/3/2.
 * 消费者和生产者的例子,用于说明线程之间的通信
 * 把生产者和消费者作为两个线程
 * 仓库作为一个类,有装入生产者生产的商品和向消费者提供商品两个方法
 */
public class ConsumerAndProductor {
    public static void main(String[] args) {
        Repo repo = new Repo();
        ComsumerThread comsumerThread = new ComsumerThread(repo);
        comsumerThread.start();
        ProductorThread productorThread = new ProductorThread(repo);
        productorThread.start();
    }
}

class Repo {
    //仓库可以容纳6件商品
    char[] data = new char[6];
    int index = 0;

    public synchronized void in(char c) {
        if (index == 6) {
            try {
                this.wait();
                System.out.println("-----" + this);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        data[index++] = c;
        System.out.println("生产了产品" + c);
        this.notify();
    }

    public synchronized char out() {
        if (index == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        index--;
        System.out.println("消费了产品" + data[index]);
        this.notify();
        return data[index];
    }
}

class ComsumerThread extends Thread {
    Repo repo;

    ComsumerThread(Repo repo) {
        this.repo = repo;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            char c = (char) (Math.random() * 26 + 'A');
            repo.in(c);
            try {
                Thread.sleep((int) (Math.random() * 10));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class ProductorThread extends Thread {
    Repo repo;

    ProductorThread(Repo repo) {
        this.repo = repo;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            repo.out();
            try {
                Thread.sleep((int) (Math.random() * 100));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

图片说明
运行结果:
图片说明
既然是有wait方法,那就应该是对应的线程对象吧,可是打印出来又是自己创建的Repo对象,懵了

  • 写回答

3条回答 默认 最新

  • 毕小宝 博客专家认证 2016-03-02 23:56
    关注
       this是指当前对象本身,你给出的这个in方法是你的Repo类的,你通过这个对象调用in方法,肯定这个方法中的this对象就是这个仓库对象啊。所有类的方法中出现的this都是这个方法调用时.操作前面的对象。这就是为什么我们调用类的方法是必须先创建一个对象,然后通过对象.方法来调用的原因。
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 数学的三元一次方程求解
  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题