「已注销」 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 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置