Why do variables passed to runnable need to be final?

前端 未结 3 437
走了就别回头了
走了就别回头了 2020-12-03 18:07

If I have a variable int x = 1, say, and I declare a runnable in the main thread, and I want to pass x to the runnable\'s run() method, it must be

3条回答
  •  时光取名叫无心
    2020-12-03 18:38

    Because if they are able to be changed, it could cause a lot of problems, consider this:

    public void count()
    {
        int x;
    
        new Thread(new Runnable()
        {
            public void run()
            {
                while(x < 100)
                {
                    x++;
                    try
                    {
                        Thread.sleep(1000);
                    }catch(Exception e){}
                }
            }
         }).start();
    
         // do some more code...
    
         for(x = 0;x < 5;x++)
             for(int y = 0;y < 10;y++)
                 System.out.println(myArrayElement[x][y]);
     }
    

    This is a rough example but you can see where a lot of unexplained errors could occur. This is why the variables must be final. Here is a simple fix for the problem above:

    public void count()
    {
        int x;
    
        final int w = x;
    
        new Thread(new Runnable()
        {
            public void run()
            {
                int z = w;
    
                while(z < 100)
                {
                    z++;
                    try
                    {
                        Thread.sleep(1000);
                    }catch(Exception e){}
                }
            }
         }).start();
    
         // do some more code...
    
         for(x = 0;x < 5;x++)
             for(int y = 0;y < 10;y++)
                 System.out.println(myArrayElement[x][y]);
     } 
    

    If you want a more full explanation, it is sort of like synchronized. Java wants to prevent you from referencing one Object from multiple Threads. Here is a little bit about synchronization:

    • http://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html

    Hope this helped!

提交回复
热议问题