对于循环括号

Pay*_*sal 12 java for-loop

public class MultithreadingFour {
        public static void main(String args[]){
                A obj = new A();
                Task task= new Task();
                for(int i=0; i<10; i++)
                        Thread t= obj.newThread(task);
        }
}
Run Code Online (Sandbox Code Playgroud)

编译错误:此行有多个标记

Syntax error, insert ";" to complete Statement
  t cannot be resolved to a variable
Syntax error, insert "AssignmentOperator Expression" to complete Assignment
Syntax error, insert ":: IdentifierOrNew" to complete ReferenceExpression
  Thread cannot be resolved to a variable
Run Code Online (Sandbox Code Playgroud)

public class MultithreadingFour {
        public static void main(String args[]){
                A obj = new A();
                Task task= new Task();
                for(int i=0; i<10; i++){
                        Thread t= obj.newThread(task);
                }
        }
}
Run Code Online (Sandbox Code Playgroud)

编译成功(注意for循环中添加的花括号).

Pau*_*ton 13

在Java中,变量声明Thread t = ...在技​​术上不是语句,而块{ ... }是.以下内容for ( ... )必须是一个声明.


Jea*_*ard 8

"for statement"的主体必须是"声明".

局部变量声明不是声明.因此,您不能将局部变量声明作为"for语句"的"声明".

这是for循环的允许语法:

BasicForStatement:for(ForInitopt; Expressionopt; ForUpdateopt)Statement

ForStatementNoShortIf:for(ForInitopt; Expressionopt; ForUpdateopt)StatementNoShortIf

您可能需要阅读JLS 14.块和语句以获取更多信息.

考虑一下,在单行for循环中允许变量声明是不合逻辑的,因为它永远不能访问它,因为它仅在循环范围内可用.