×

Loading...
Ad by
  • 最优利率和cashback可以申请特批,好信用好收入offer更好。请点链接扫码加微信咨询,Scotiabank -- Nick Zhang 6478812600。
Ad by
  • 最优利率和cashback可以申请特批,好信用好收入offer更好。请点链接扫码加微信咨询,Scotiabank -- Nick Zhang 6478812600。

老大,你可以用类工厂解决这个问题呀!Class Factory。楼上的兄弟全都把简单的问题复杂化了,没那个必要

本文发表在 rolia.net 枫下论坛首先声明一个工厂类,把这个类作为一个全局变量,以后生成 CarA全部通过这个工厂类来实现,就能达到控制的目的

public calss ClassFactory
{
static bool IsCarAExist=false;
public CarA GetCarA()
{
if( IsCarAExist == false)
{
IsCarAExist = true;
return new CarA();
}
else {
return null;
}
}
}

工厂类应该是“设计模式”最基本的概念,了解一下很有用。

在程序运行时,首先声称这个工厂类,然后在每一个线程内生成CarA class 时用这个工厂类的 GetCarA()函数来完成,当 GetCarA 第一次运行并返回一个 CarA class时,工厂类的static bool IsCarAExist 变为 true. 这样当Thread2 第二次试图用GetCarA() 返回 CarA 类时就会发现已经生成过这样一个类,因而返回null.
我是用C#的思想做的,但java和C#非常相近,估计楼主应该能看懂。具体程序大概如下:

public class Test
{

ClassFactory classFactory=new ClassFactory();

public static void Main()
{
Thread thread1=new thread(ProcessThread1); //确定线程1的运行函数,ProcessThread1()
Thread thread2=new thread(ProcessThread2); //确定线程2的运行函数,ProcessThread2()

thread1.Strat(); // 启动线程一
thread2.Start(); // 启动线程二
}

public void ProcessThread1()
{
CarA carA=classFactory.GetCarA(); // 由工厂类生成 CarA
.....
}

public void ProcessThread2()
{
CarA carA=classFactory.GetCarA();
if (CarA==null)
{
// CarA类已经被创建过一次了
}
}

}更多精彩文章及讨论,请光临枫下论坛 rolia.net
Report

Replies, comments and Discussions:

  • 工作学习 / 专业技术讨论 / 请教一个JAVA问题: 同一个JVM, 有不同的THREAD. 有没有什么办法可以找到其它thread正在使用的一个Object ?
    比如, Object 是一个Car Class. 我们用 CarA, CarB, CarC... 来表示这个Class中的不同object.

    Thread 1 可能会调出 CarA. 当 Thread 2 运行时, 它能否判断出当前JVM中有一个object: CarA ? 用什么办法?

    俺考虑过用 Singleton Pattern, 但那个需要CarA 一直常驻在JVM中. 俺不希望这样. 俺只想 CarA 在被需要时调出, 不需要时就被garbage collection 清掉.

    先谢过!
    • If CarA is orphan but still in the JVM due to undetermined garbage collector behavior, do you still want Thread2 detects it?
      • No. What I need is, for Thread 2, find out whether CarA is being invoked by another thread.
        • is there any way to access JVM's heap or something like that?
        • One of CarA's method is being called by another thread not nesessay thread1? how about you make CarA a monitor, in thread2 check holdslock?
    • does Java support such low level object recognization? I dont know Java well, maybe some kind reflection may help. Does Java support this?
    • 可以搞一个pool池, 或者类似的做法, thread create carA 后,把carA放入一个collection中
      • 俺想过这主意, 关键是当CarA没人用了的时候, 也还会占一个位置在池里.
        • how about stack? in car class, when destructor is called, pop stack
    • C里面应该使用semaphore 可以实现。JDK 5 里面有个semaphore,似乎是干这个的。很久没有用过Java了,不很了解。
      • PS: java.util.concurrent.Semaphore
        • 高手啊. 俺只用到1.4.
          • 呵呵.不是高手.偶用的时候还是1.3刚出来。
    • why not singleton? when count goes down to 0, force GC.
      • if you read the code for JDK implementation, System.gc() does not do the garbage collection any more
        JDK with version higher than 1.1 NEVER EVER guarantees the call into System.gc() tiggers the garbage collection. In fact, you can NOT force a garbage collection.
    • Use pool with weak reference.
      • support this one
      • Thanks~~~ I believe this is the correct direction.
        • if u dont care about life time, and dont want to reuse it, how about use a global counter, add code in ctor, that's it. not OO approach though.
          • if you want to know excat how many, use finalize ()
            • LOL...钉...LOL....建议你去哪个什么学校retraining一下...
              • 英文要跟jerry学,难道中文也不行了么?--- “俺想过这主意, 关键是当CarA没人用了的时候, 也还会占一个位置在池里.”
                • 说你不如改行的还死嘴硬。算了,给你个意见,爱听不听,#2851596。多帮帮同胞,技术谁做不一样,别把机会给外人。
                  • 你也别嘴硬。拿出code来看看。你的pool of weak reference 根本就是多余。他的要求根本不需要一个pool.只需要一个引用计数。
                    • 我一般和面食官聊聊,PPMP,然后就刷网,Boss说,那不造假的,都要写程序,那辛苦Retrain过的,就监工好了。
                      • 对阿队啊,听说监工都喜欢杀鸡用牛刀的。明明简单的东西非要把老师交给的最复杂的拿来用用
                        • hiahia.
          • No wonder you cannot beat a "造假人士" ... lol ... 如果你到我这面食,你肯定不过...随便找个retraining的都比你强太多。找不到工作的,要么象你,要么就是太老实。对了,我就是一个靠假简历改行的,大家认识一下。LOL.....
            • haha, before u LOL... according to his original requirement, he only wants to know at a certain time, how many Cars are created.
              He event does not care about whether afterwards, the existing car will disappear. what's use for your pool though in this case?
              • 钉。
    • 感谢以上各位大侠的热心相助. 献歌一首, 谨表谢意: #2856530@0
      • 我喜欢实惠的,比如一麻袋西兰花
    • Java本人不会。不过Singleton不需要常驻内存。那个JVM是不是一个类似Process的东东?如果是的话Singleton+记数+Mutex是个好方法,不过Car的门要小,线程之间通讯的Rule要清晰,防止死锁。只是不知道Java里面有无delete this。
      • 其实不用singleton,用singleton反而违背他的初衷。计数加锁就可以了。你在哪里delete this? java 不是c++.因为不知道他要这个计数干什么用,所以计数加锁是最简单的。
        • 忘了说一句。如果他真的需要这个计数来控制同时存在的object数目, technique similar to singleton applies.
        • 不是说了么本人不会Java. 不过语言本身应该和C++差不多吧?其实表面上的方法多了,但是实现起来最重要最麻烦的东西只有一个,多线程设计。我的经验是多线程之间最好不要玩这些,得不偿失。
          • 我也不是学java的。an article says singleton in Java has memory leak.
            http://churchillobjects.com/c/11043f.html
            • correction, this article did not mention memory leak.
    • 我们都上sailor当拉
      如果他的要求具体是这样的
      thread1()
      {
      carA = new Car();
      }

      thread2()
      {
      carB = new Car();
      .....
      I want to know whether there is a carA created by thread1 and only by thread1?
      Oooooooooooops.
      }

      什么引用计数啊,singleton啊, weakreference阿全完了。

      sailor老大,要求含糊,你的题目暂时无解。
      • 主说,汗...无语.
        • 给你长点知识去吧, xxx 学校的假行家们绝对不教的 ---
          你要告诉他java里面singleton不是常驻的才哈哈哈巴。

          听说xxx学校学员从教会来得也不少。
          当然他们去教会的原始目的肯定不是为了信教。
          --为了生存权。
          • 神说,无知不是你的错,那Java,太难的干活。
      • 哈哈,才看明白。真不知道楼主想干嘛。
    • 老大,你可以用类工厂解决这个问题呀!Class Factory。楼上的兄弟全都把简单的问题复杂化了,没那个必要
      本文发表在 rolia.net 枫下论坛首先声明一个工厂类,把这个类作为一个全局变量,以后生成 CarA全部通过这个工厂类来实现,就能达到控制的目的

      public calss ClassFactory
      {
      static bool IsCarAExist=false;
      public CarA GetCarA()
      {
      if( IsCarAExist == false)
      {
      IsCarAExist = true;
      return new CarA();
      }
      else {
      return null;
      }
      }
      }

      工厂类应该是“设计模式”最基本的概念,了解一下很有用。

      在程序运行时,首先声称这个工厂类,然后在每一个线程内生成CarA class 时用这个工厂类的 GetCarA()函数来完成,当 GetCarA 第一次运行并返回一个 CarA class时,工厂类的static bool IsCarAExist 变为 true. 这样当Thread2 第二次试图用GetCarA() 返回 CarA 类时就会发现已经生成过这样一个类,因而返回null.
      我是用C#的思想做的,但java和C#非常相近,估计楼主应该能看懂。具体程序大概如下:

      public class Test
      {

      ClassFactory classFactory=new ClassFactory();

      public static void Main()
      {
      Thread thread1=new thread(ProcessThread1); //确定线程1的运行函数,ProcessThread1()
      Thread thread2=new thread(ProcessThread2); //确定线程2的运行函数,ProcessThread2()

      thread1.Strat(); // 启动线程一
      thread2.Start(); // 启动线程二
      }

      public void ProcessThread1()
      {
      CarA carA=classFactory.GetCarA(); // 由工厂类生成 CarA
      .....
      }

      public void ProcessThread2()
      {
      CarA carA=classFactory.GetCarA();
      if (CarA==null)
      {
      // CarA类已经被创建过一次了
      }
      }

      }更多精彩文章及讨论,请光临枫下论坛 rolia.net
    • 好吧,我承认我太闲
      import java.util.Map;
      import java.util.WeakHashMap;

      import org.apache.commons.logging.Log;
      import org.apache.commons.logging.LogFactory;

      /**
       * Factory to generate weak referenced singleton instances. <p/> Sample Usage:
       
       <pre>
       * class ClassA {
       *    //contents here
       * }
       
       * class UserClass {
       *    public void classAUser() {
       *       ClassA classA = (CarA) SingletonFactory.getInstance()
       *             .getSingletonInstanceOf(ClassA.class);
       *    }
       * }
       </pre>
       
       @see java.lang.ref
       @see java.util.WeakHashmap
       
       */
      public class SingletonFactory {
         private static Log log = LogFactory.getLog(SingletonFactory.class);
         private static Map map = new WeakHashMap();
         private static SingletonFactory instance = new SingletonFactory();

         private SingletonFactory() {
            //intended
         }

         /**
          @return instance of SingletonFacotry
          */
         public static SingletonFactory getInstance() {
            return instance;
         }

         /**
          * Synchronzied method to instantiate object or get if exist.
          
          @param clazz Class for which to get instance. The method uses reflection
          *           to instantiate the class, so clazz should have a default
          *           constructor accessable by this factory.
          @return Instance generated or got from registry
          @see java.lang.Reflection
          */
         public synchronized// TODO could use volatile and/or Semaphore to improve
         // performance in JDK5.0+
         Object getSingletonInstanceOf(Class clazz) {

            if (null == clazz)
               throw new IllegalArgumentException("need a valid Class");

            Object object = map.get(clazz.getName());
            if (null == object) {
               try {
                  object = clazz.newInstance();
               catch (InstantiationException e) {
                  log.fatal("cannot instantiate Class " + clazz.getName());
                  throw new RuntimeException(e);
               catch (IllegalAccessException e) {
                  log.fatal("illegal access to Class " + clazz.getName());
                  throw new RuntimeException(e);
               }
               map.put(clazz.getName(), object);
               log.debug("new object of " + clazz.getName() "created");
            }
            return object;
         }
      }
      • 老大,你的html preview的效果和最后出来的不太一样哦
      • 嘿嘿,到底还实用的类工厂。不懂Java,但我估计你用到了.Net中反射的概念
      • 又是map的又是singleton的
    • 都java5乐,玩点高级的八
      是示意代码,不保证准确性

      template<typename T> class CAR
      {
      public:
      CAR()
      {
      T::IncreaseInstance();

      }

      finalize()
      {
      T::DecreaseInstance();
      }
      }

      T 是什么就大家喜欢啦。。。。
      • 这是java?不像啊,就算jdk1.5也没这东西。
    • 我比较鄙视那些张口就说design parttern的,其实都是些唬人的东西。只要学习过工程学里面那点小玩意算个啥
      • 汗,被鄙视了一把...其实我没学过设计模式,只是看过前言和目录而已..呵呵
        • 都是些什么乱七八糟的,这么简单的问题弄了这么一大堆
      • patterns有点像成语,适当的地方用个成语就能把个挺复杂的事情说清楚。过度使用甚至误用当然不是好事,但是因为自己不懂成语而鄙视人家用成语,就...
        • 求教!
          能人好多啊! 公司还在用VB,PB; 应用的主要功能是生成各种报表. 今年老板突然想搞Web应用.本人愚笨,只知道用form取/送数据(从/到DB). 各位能否指教如何在Web应用生成各种报表,而且要Excel形式的,最好用java技术. 介绍书或网站也行, 来加好不容易找到的工作怕丢了,只能笨鸟先学了. 先谢了!