public class Even {
static private int i;
public synchronized void next() {i++;i++;}
public synchronized int getValue() { return i;}
public static void main(String[] args) {
final Even cal =new Even();
new Thread("Watcher") {
public void run() {
while (true) {
int val=cal.getValue(); //1,因为cal是final的,匿名类才可访问,否则编译出错!
if(val%2!=0) {
System.out.println(val);
System.exit(0);
}
}
}
}.start();
while(true) cal.next(); //2,这句是死循环,main线程永远执行!其实Wacther线程也不会退出,因为i=0,2,4,6,8....如果你能等到i溢出的时候,程序也许会结束。
}
}
static private int i;
public synchronized void next() {i++;i++;}
public synchronized int getValue() { return i;}
public static void main(String[] args) {
final Even cal =new Even();
new Thread("Watcher") {
public void run() {
while (true) {
int val=cal.getValue(); //1,因为cal是final的,匿名类才可访问,否则编译出错!
if(val%2!=0) {
System.out.println(val);
System.exit(0);
}
}
}
}.start();
while(true) cal.next(); //2,这句是死循环,main线程永远执行!其实Wacther线程也不会退出,因为i=0,2,4,6,8....如果你能等到i溢出的时候,程序也许会结束。
}
}
Thread threadName=new Thread(***),
里面的星号一般是用什么?在这里的Wacther是随便给的吧?帮我看看下面三个例子,我是初学者,能不能给我解释一下?加分了,谢谢!
public class Even {
private int i;
public void next() {i++;i++;}
public int getValue() { return i;}
public static void main(String[] args) {
final Even cal =new Even();
new Thread("Watcher") {
public void run() {
while (true) {
int val=cal.getValue();
if(val%2!=0) {
System.out.println(val);
System.exit(0);
}
}
}
}.start();
while(true) cal.next();
}
}
这个例子能终止并且每次终止的位置不同,因为有线程的不确定性问题,但我不理解的是:
线程start后执行run,val=0,马上就执行完了,线程也就执行完了,后面的while(true) cal.next();则不停执行,但已经与线程没关系,显然不对的,说说具体是怎么执行的吗?public class Even {
static private int i;
public synchronized void next() {i++;i++;}
public synchronized int getValue() { return i;}
public static void main(String[] args) {
final Even cal =new Even();
new Thread("Watcher") {
public void run() {
while (true) {
int val=cal.getValue();
if(val%2!=0) {
System.out.println(val);
System.exit(0);
}
}
}
}.start();
while(true) cal.next();
}
}这个例子是死循环public class Even {
static private int i;
public synchronized void next() {i++;i++;}
public synchronized int getValue() { return i;}
public static void main(String[] args) {
new Thread("Watcher") {
public void run() {
while (true) {
int val=even.getValue();
if(val%2!=0) {
System.out.println(val);
System.exit(0);
}
}
}
}.start();
while(true) next();//注意这里是不同的
}
}
这个例子执行的结果又是怎么样呢?
毛病在上面一句,因为初始化时i=0,而你的两个i++使i永远为偶数,所以
if(val%2!=0) {
System.out.println(val);
System.exit(0);
}
无法输出结果,也无法执行System.exit(0);直到i一处为止。
建议修改程序如下:
public class Even {
static private int i;
public synchronized void next() {i++;}//此处只有一个i++能达到你的要求退出了
public synchronized int getValue() { return i;}
public static void main(String[] args) {
final Even cal =new Even();//1.final在这里的作用是什么?
new Thread("Watcher") {
public void run() {
while (true) {
int val=cal.getValue();
if(val%2!=0) {
System.out.println(val);
System.exit(0);
}
}
}
}.start();
while(true) cal.next();
}
}
有联系的,例如:
public synchronized void next()
和
public synchronized int getValue() { return i;}