倒了。 你这里的load.change(count);的这个load没有实例话,是个空对象阿。他不是着不到count而是找不到load。你可以这样改的 class Counter extends Thread{ CounReload load=new CounReload(); String name; public static int count=0; ......
import java.io.*; public class bean5 { public static void main(String args[]){ new Counter("A"); new Counter("B"); new Counter("C"); new Counter("D"); try{Thread.sleep(10000);} catch(InterruptedException e){} } } class Counter extends Thread{ CounReload load; String name; int count=0; Counter(String name){ this.name=name; new Thread(this,"dfds").start(); } public void run(){ while(true){ System.out.print(name+" "); new CounReload().change(count++); try{Thread.sleep(100);} catch(InterruptedException e){} } } } class CounReload{ synchronized void change(int c){ System.out.println("count: "+c); } }
/*** 名称和 count 的数值有时会错开, 你可能需要吧名字输出也加到同步方法中去. **/ import java.io.*; public class T1 { public static void main(String args[]){ CounReload load = new CounReload(); new Counter(load, "A"); new Counter(load, "B"); new Counter(load, "C"); new Counter(load, "D");
你这里的load.change(count);的这个load没有实例话,是个空对象阿。他不是着不到count而是找不到load。你可以这样改的
class Counter extends Thread{
CounReload load=new CounReload();
String name;
public static int count=0;
......
public class bean5 {
public static void main(String args[]){
new Counter("A");
new Counter("B");
new Counter("C");
new Counter("D");
try{Thread.sleep(10000);}
catch(InterruptedException e){}
}
}
class Counter extends Thread{
CounReload load;
String name;
int count=0;
Counter(String name){
this.name=name;
new Thread(this,"dfds").start();
}
public void run(){
while(true){
System.out.print(name+" ");
new CounReload().change(count++); try{Thread.sleep(100);}
catch(InterruptedException e){}
}
}
}
class CounReload{
synchronized void change(int c){
System.out.println("count: "+c);
}
}
名称和 count 的数值有时会错开, 你可能需要吧名字输出也加到同步方法中去. **/
import java.io.*;
public class T1 {
public static void main(String args[]){
CounReload load = new CounReload();
new Counter(load, "A");
new Counter(load, "B");
new Counter(load, "C");
new Counter(load, "D");
try{
Thread.sleep(10000);
}catch(InterruptedException e){
}
System.exit(0);
}
}class Counter extends Thread{
CounReload load;
String name; Counter(CounReload load , String name){
this.name=name;
this.load = load;
new Thread(this,"dfds").start();
}
public void run(){
while(true){
System.out.print(name+" ");
load.change();
try{
Thread.sleep(100);
}catch(InterruptedException e){
}
}
}
}
class CounReload{
// define count here
int count = 0;
// synchronized method
synchronized int change(){
count++;
System.out.println("count: "+count);
return count;
}
}
我还想问一下,为什么不能把count定义在T1内中?
我把它定义成public 也不行,
不是说public 在其他类中也是可用的吗?为什么它还说找不到变量count?