如何通过一个解释程序模拟
Thread
的行为?目前我想到了以下方法: AstInterpreter应该实现
java.lang.Runnable
。它还应该重写每个java.lang.Thread
(或其子类)的新实例表达式,将Thread
的目标(java.lang.Runnable
)替换为新的AstInterpreter实例:
编辑:提供更复杂的示例。
编辑2:备注1。
目标程序:class PrintDemo {
public void printCount(){
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter --- " + i );
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
}
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
PrintDemo PD;
ThreadDemo( String name, PrintDemo pd){
threadName = name;
PD = pd;
}
public void run() {
synchronized(PD) {
PD.printCount();
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start ()
{
System.out.println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
PrintDemo PD = new PrintDemo();
ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );
ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );
T1.start();
T2.start();
// wait for threads to end
try {
T1.join();
T2.join();
} catch( Exception e) {
System.out.println("Interrupted");
}
}
}
程序1(ThreadTest - 字节码解释):
new Thread( new Runnable() {
public void run(){
ThreadTest.main(new String[0]);
}
});
程序2(ThreadTest-AST解释):
final com.sun.source.tree.Tree tree = parse("ThreadTest.java");
new Thread( new AstInterpreter() {
public void run(){
interpret( tree );
}
public void interpret(com.sun.source.tree.Tree javaExpression){
//...
}
});
请问生成的程序2是否能够正确模拟初始程序1中线程的行为?
1) 目前只接受source=8 / target=8
的方案。
ArrayBlockingQueue
)实现的2线程生产者-消费者模式。 - Victor Sorokin