我正在为 Java 6*1) 开发转换器,它执行一种部分评估,但为了简单起见,让我们考虑一下, Java 程序的抽象语法树解释。
如何通过解释型程序模拟线程
的行为?
目前我的想法是:
AstInterpreter 应该实现 java.lang.Runnable
。它还应该重写 java.lang.Thread
(或其子类)的每个新实例表达式,替换 Thread
的目标(java.lang.Thread)。 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
方案被接受。
最佳答案
我看到两个选项:
选项 1:JVM 线程。每次解释程序调用 Thread.start 时,您也会调用 Thread.start 并使用另一个解释器启动另一个线程。这很简单,使您不必实现锁定和其他事情,但您的控制力会减少。
选项 2:模拟线程。类似于在单处理器上实现多任务处理的方式——使用时间片。您必须在解释器中实现锁定和 hibernate ,并跟踪模拟线程以了解哪些线程已准备好运行、哪些已完成、哪些被阻塞等。
您可以执行一个线程的指令,直到它阻塞或经过一段时间或达到某个指令计数,然后找到另一个可能正在运行的线程并切换到运行该线程。在操作系统的上下文中,这称为进程调度 - 您可能想研究这个主题以获取灵感。
关于java - 模拟 java.lang.Thread 的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34606850/