分析Java中的线程行为

时间:2009-09-03 11:31:13

标签: java multithreading concurrency

我需要绘制两个并发运行线程的写访问图。将这些访问的时间戳值对写入数组的最佳方法是什么,而不会干扰线程本身?正在编写的队列如下所示:

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;
    }
}

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

1 个答案:

答案 0 :(得分:1)

一种可能性是使用 BTrace ,用于动态(字节码)检测正在运行的Java程序的类。
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!");
    }
}