2009-09-03 58 views
1

我需要画出两个并发运行的线程的写入访问图。将这些访问的时间戳值对写入数组的最佳方式是什么,而不会干扰线程本身?正在写入的队列看起来像这样:分析Java中的线程行为

import java.util.concurrent.atomic.AtomicInteger; 

class IQueue<T> { 
    AtomicInteger head = new AtomicInteger(0); 
    AtomicInteger tail = new AtomicInteger(0); 
    T[] items = (T[]) new Object[100]; 

    public void enq(T x) { 
     int slot; 
     do { 
      slot = tail.get(); 
     } while (! tail.compareAndSet(slot, slot+1)); 
     items[slot] = x; 
    } 

    public T deq() throws EmptyException { 
     T value; 
     int slot; 
     do { 
      slot = head.get(); 
      value = items[slot]; 
      if (value == null) 
       throw new EmptyException(); 
     } while (! head.compareAndSet(slot, slot+1)); 
     return value; 
    } 

    public String toString() { 
     String s = ""; 
     for (int i = head.get(); i < tail.get(); i++) { 
      s += items[i].toString() + "; "; 
     } 
     return s; 
    } 
} 

我想记录线程何时开始/停止写入。

+0

使用'LinkedBlockingQueue' /'ArrayBlockingQueue'有什么问题? – pjp 2009-09-03 11:47:13

+0

btrace可以作为代理程序预编译并附加到程序的开始部分。 – VonC 2009-09-03 12:46:24

+0

这是一个教育演习。 – pypmannetjies 2009-09-03 12:52:33

回答

1

对于正在运行的Java程序的动态(字节码)工具类,一种可能性是使用BTrace
BTrace将追踪操作插入正在运行的Java程序的类中,并热插拔跟踪的程序类。

// import all BTrace annotations 
import com.sun.btrace.annotations.*; 
// import statics from BTraceUtils class 
import static com.sun.btrace.BTraceUtils.*; 

// @BTrace annotation tells that this is a BTrace program 
@BTrace 
public class HelloWorld { 

    // @OnMethod annotation tells where to probe. 
    // In this example, we are interested in entry 
    // into the Thread.start() method. 
    @OnMethod(
     clazz="java.lang.Thread", 
     method="start" 
    ) 
    public static void func() { 
     // println is defined in BTraceUtils 
     // you can only call the static methods of BTraceUtils 
     println("about to start a thread!"); 
    } 
} 
+0

这很有趣。但是,它必须作为一个java程序自行运行,并且必须从命令行运行btrace ...所以这不是一个选项。 :( – pypmannetjies 2009-09-03 12:45:16