第一队和第二队都有id 0吗?我究竟做错了什么?我只是想在每次创建一个新对象时自动增加id.
这是Team.java的代码
public class Team{
private int teamId;
public Team(){
this.teamId= teamId++;
}
public void printTeamId(){
System.out.println(this.teamId);
}
}
Run Code Online (Sandbox Code Playgroud)
这是来自Main.java的代码
public class Main {
public static void main(String[] args) {
Team one= new Team();
Team two= new Team();
one.printTeamId();
two.printTeamId();
}
}
Run Code Online (Sandbox Code Playgroud)
您需要一个额外的静态变量来存储团队数量.Static表示所有对象共享此变量.每个团队都拥有自己的变量teamId,但共享变量teamIdCounter
public class Team{
private int teamId;
private static int teamIdCounter = 0;
public Team(){
this.teamId= teamIdCounter++;
}
public void printTeamId(){
System.out.println(this.teamId);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您使用多个线程,请检查有关如何使用AtomicInteger计算对象线程安全的其他答案.
关于静态变量是可以的,但是如果您想确保线程安全,请使用Atomic Integer。
public class Team{
private int teamId;
private static AtomicInteger atomicInteger = new AtomicInteger(0);
public Team(){
this.teamId= atomicInteger.incrementAndGet();
}
public void printTeamId(){
System.out.println(this.teamId);
}
}
Run Code Online (Sandbox Code Playgroud)
这将使线程安全计数器变为不是线程安全的静态计数器。