我正在尝试运行这三个并发线程,但是当我执行 system.print 时 Char 不会出来,计数器“i”越界。
不知何故,我在 Char 前面添加了一个字符串,它打印正确,任何人都可以向我解释为什么会发生这种情况?
public class Part2 {
public static void main(String[] args) {
Runnable printA = new PrintChar('a');
Runnable printB = new PrintChar('b');
Runnable printC = new PrintChar('c');
Thread t1 = new Thread(printA);
Thread t2 = new Thread(printB);
Thread t3 = new Thread(printC);
t1.start();
t2.start();
t3.start();
}
private static class PrintChar implements Runnable {
private char c;
public PrintChar(char c) {
this.c = c;
}
public void run()
{
for(int i = 1; i<=100; i++) {
System.out.print(c + i + ", ");
}
}
}
}
/*这是这段代码的输出: 98, 100, 101, 102, 103, 104, 105, 99, 99, .... 198, */
/*如果我像这样在 Char 之前添加一个字符串 这是我期望的输出; */
public void run()
{
for(int i = 1; i<=100; i++) {
System.out.print("" + c + i + ", ");
}
}
/* b1, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18,....
a1~a100
b1~b100
且c1~c100同时运行完成*/
最佳答案
当您在 char
和 int
上使用 +
运算符时,它执行算术加法,而不是字符串连接。首先放置 ""+
意味着您首先执行 ""+ c
,即串联成 String
,然后添加该 String
到 int
,这是另一种串联。
关于java - 为什么 Char 不会打印,并且计数器超出了我的循环;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56104516/