直接调用 thread 对象的 run() 方法不会启动单独的线程,并且可以在当前线程内执行。要从单独的线程中执行 runnable.run,请执行以下操作之一
使用 runnable 构造一个线程> 对象并调用 thread 上的 start() 方法。定义 thread 对象的子类并覆盖其 run() 方法的定义。然后构造该子类的实例并直接调用该实例的 start() 方法。示例public class threadrunmethodtest { public static void main(string args[]) { mythread runnable = new mythread(); runnable.run(); // call to run() method does not start a separate thread system.out.println("main thread"); }}class mythread extends thread { public void run() { try { thread.sleep(1000); } catch (interruptedexception e) { system.out.println("child thread interrupted."); } system.out.println("child thread"); }}
在上面的示例中,主线程 threadrunmethodtest 使用 run() 方法调用子线程 mythread。这会导致子线程在主线程的其余部分执行之前运行完成,以便在“main thread”之前打印“child thread”。输出child threadmain thread
以上就是如果我们直接调用java中的run()方法会发生什么?的详细内容。