在下面的stacktrace程序中获得异常

时间:2017-01-05 05:25:48

标签: java multithreading

我已经开发了程序来证明如果线程和它在静态同步方法中仍然有一个线程可以从java本身的那个方法进入其他静态同步方法但我的程序抛出异常请告知它出了什么问题,下面是代码

package com.synchrnozie;

class MyRunnable18 implements Runnable {

    @Override
    public void run() {
        method1();
    }

    static synchronized void method1() {
        System.out.println("static synchronized void method1() started");
        method2();
        System.out.println("static synchronized void method1() ended");
    }

    static synchronized void method2() {
        System.out.println("in static synchronized method2()");
        method3();
    }

    static synchronized void method3() {
        System.out.println("in static synchronized method3()");
        method3();
    }

}

public class staticNesting {
    public static void main(String args[]) throws InterruptedException {
        MyRunnable18 MyRunnable18 = new MyRunnable18();
        Thread thread1 = new Thread(MyRunnable18, "Thread-1");
        thread1.start();
    }

}

以下是异常堆栈跟踪..

Exception in thread "Thread-1" java.lang.StackOverflowError
    at sun.nio.cs.SingleByte.withResult(Unknown Source)
    at sun.nio.cs.SingleByte.access$000(Unknown Source)
    at sun.nio.cs.SingleByte$Encoder.encodeArrayLoop(Unknown Source)
    at sun.nio.cs.SingleByte$Encoder.encodeLoop(Unknown Source)
    at java.nio.charset.CharsetEncoder.encode(Unknown Source)
    at sun.nio.cs.StreamEncoder.implWrite(Unknown Source)
    at sun.nio.cs.StreamEncoder.write(Unknown Source)
    at java.io.OutputStreamWriter.write(Unknown Source)
    at java.io.BufferedWriter.flushBuffer(Unknown Source)
    at java.io.PrintStream.write(Unknown Source)
    at java.io.PrintStream.print(Unknown Source)
    at java.io.PrintStream.println(Unknown Source)
    at com.synchrnozie.MyRunnable18.method3(staticNesting.java:24)
    at com.synchrnozie.MyRunnable18.method3(staticNesting.java:25)

2 个答案:

答案 0 :(得分:1)

你的methode3()调用方法3()无限,也许这就是为什么?

答案 1 :(得分:1)

您正在对method3进行递归调用,这会导致stackoverlflow错误。

 static synchronized void method3() {
            System.out.println("in static synchronized method3()");
            method3();
        }