2009-09-03 47 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