review36
Posted liaoxiaolao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了review36相关的知识,希望对你有一定的参考价值。
对于Thread(Runnable target)构造方法创建的线程,轮到它来享用CPU资源时,目标对象就会自动调用接口中的run()方法,因此,对于使用同一目标对象的线程,目标对象的成员变量自然就是线程共享的数据单元。
下面的例子中,房屋就是线程的目标对象,房屋中的一桶水被猫和狗共享。
public class Test07 { public static void main(String[] args) { // TODO Auto-generated method stub House house = new House(); house.setWater(10); Thread dog, cat; dog = new Thread(house); cat = new Thread(house); dog.setName("狗"); cat.setName("猫"); dog.start(); cat.start(); } }
House.java
public class House implements Runnable { int waterAmount; public void setWater(int w) { waterAmount = w; } @Override public void run() { // TODO Auto-generated method stub while(true) { String name = Thread.currentThread().getName(); if(name.equals("狗")) { System.out.println(name + "喝水"); waterAmount = waterAmount -2; } else if(name.equals("猫")) { System.out.println(name + "喝水"); waterAmount = waterAmount - 1; } System.out.println(" 剩 " + waterAmount); try{ Thread.sleep(2000); } catch(InterruptedException e){} if(waterAmount <= 0) { return; } } } }
运行结果如下所示:
目标对象可以组合线程,即将线程作为自己的成员(弱耦合)。
可以这样改
public class Test01 { public static void main(String[] args) { // TODO Auto-generated method stub House house = new House(); house.setWater(10); house.dog.start(); house.cat.start(); } }
House.java
public class House implements Runnable { int waterAmount; Thread dog, cat; House() { dog = new Thread(this); cat = new Thread(this); } public void setWater(int water) { waterAmount = water; } @Override public void run() { // TODO Auto-generated method stub while(true) { Thread thread = Thread.currentThread(); if(thread == dog) { System.out.println("家狗喝水 -2"); waterAmount = waterAmount - 2; } else if(thread == cat) { System.out.println("家猫喝水 -1"); waterAmount = waterAmount - 1; } try{ Thread.sleep(2000); } catch(InterruptedException e){} if(waterAmount <= 0) { return; } } } }
运行结果如下所示:
以上是关于review36的主要内容,如果未能解决你的问题,请参考以下文章
git error unpack failed git review to gerrit 上缺少 blob