当前位置: 技术问答>java相关
关于线程同步循环调用的问题!
来源: 互联网 发布时间:2015-05-14
本文导语: class X implements Runnable{ private int x; private int y; public static void main(String[]args){ X that = new X(); (new Thread(that)).start();//线程1 (new Thread(that)).start(); //线程 2 } public void run()...
class X implements Runnable{
private int x;
private int y;
public static void main(String[]args){
X that = new X();
(new Thread(that)).start();//线程1
(new Thread(that)).start(); //线程 2
}
public void run(){ //换为public sychronized void run()
for (;;){
x++;
y++;
System.out.println("x=" + x + ", y = " + y);
}
}
}
What is the result?
A. Errors at lines 7 and 8 cause compilation to fail.
B. The program prints pairs of values for x and y that might not always be the same on the same line (for example, “x=2, y=1”). //**
C. The program prints pairs of values for x and y that are always the same on the same line (for example, “x=1, y=1”. In addition, each value appears twice (for example, “x=1, y=1” followed by “x=1, y=1”).
D. The program prints pairs of values for x and y that are always the same on the same line (for example, “x=1, y=1”. In addition, each value appears only for once (for example, “x=1, y=1” followed by “x=2, y=2”).
请问此题选什么?
把//处换后选什么呢?
谢谢
是否因为for 为一个无限循环,所以线程2不会执行。?
private int x;
private int y;
public static void main(String[]args){
X that = new X();
(new Thread(that)).start();//线程1
(new Thread(that)).start(); //线程 2
}
public void run(){ //换为public sychronized void run()
for (;;){
x++;
y++;
System.out.println("x=" + x + ", y = " + y);
}
}
}
What is the result?
A. Errors at lines 7 and 8 cause compilation to fail.
B. The program prints pairs of values for x and y that might not always be the same on the same line (for example, “x=2, y=1”). //**
C. The program prints pairs of values for x and y that are always the same on the same line (for example, “x=1, y=1”. In addition, each value appears twice (for example, “x=1, y=1” followed by “x=1, y=1”).
D. The program prints pairs of values for x and y that are always the same on the same line (for example, “x=1, y=1”. In addition, each value appears only for once (for example, “x=1, y=1” followed by “x=2, y=2”).
请问此题选什么?
把//处换后选什么呢?
谢谢
是否因为for 为一个无限循环,所以线程2不会执行。?
|
B。加上 同步后,选 D。
不会因为for为一个无限循环而导致线程2不执行。
证据如下:
把System.out.println("x=" + x + ", y = " + y);
改成if(x!=y) System.out.println(""+x+","+y);
结果输出一大堆东东~
不会因为for为一个无限循环而导致线程2不执行。
证据如下:
把System.out.println("x=" + x + ", y = " + y);
改成if(x!=y) System.out.println(""+x+","+y);
结果输出一大堆东东~
|
正确答案是B,如果加上同步的话答案是D
|
B
加上 同步后,
选 D
加上 同步后,
选 D
|
To xiaobi_liang(做纯粹的p2p自由软件)
你的理解是不对的,
因为只有加上synchronized标志的方法才是“所以每次只有一个被调用”。
在C++中,每个方法都是放在代码段的内存区间,每个方法调用都是先保存
当时的寄存器、返回地址等运行环境到一个叫做“活动记录”的地方,然后
进入到被调用方法的代码块中执行。
当两个线程一起运行时,同时调用一个方法,只要各自保存寄存器PC的状态
即可,这只是操作系统线程调度的问题(在Java中则是JVM的线程调度问题)。
你的理解是不对的,
因为只有加上synchronized标志的方法才是“所以每次只有一个被调用”。
在C++中,每个方法都是放在代码段的内存区间,每个方法调用都是先保存
当时的寄存器、返回地址等运行环境到一个叫做“活动记录”的地方,然后
进入到被调用方法的代码块中执行。
当两个线程一起运行时,同时调用一个方法,只要各自保存寄存器PC的状态
即可,这只是操作系统线程调度的问题(在Java中则是JVM的线程调度问题)。