public class AddInteger {
private int count = 0;
void addCount() {
int addcount = 0;
System.out.println(Thread.currentThread().getId() + Thread.currentThread().getName());
while (addcount++ < 100000) {
count += 1;
// System.out.println(count);
}
}
int getCount() {
return this.count;
}
}
public class MultithThread implements Runnable{
private AddInteger addInteger=null;
public MultithThread(AddInteger addInteger) {
this.addInteger = addInteger;
}
@Override
public void run() {
addInteger.addCount();
}
}
public class TestThread {
public static void main(String[] args) {
AddInteger addInteger = new AddInteger();
MultithThread multithThread1 = new MultithThread(addInteger);
Thread thread = new Thread(multithThread1);
Thread thread2 = new Thread(multithThread1);
thread.start();
thread2.start();
try {
thread.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(addInteger.getCount());
}
}
如上图所示
如果addCount方法内的输出行被注释掉,则最终在主方法中输出的count会小于20000,接近10000,但如果将输出行取消注释,则一定是20000,这边想半天还是没想通,日后再想
网友评论