朋友内推搜狐面试,面试题中面试官出了这样一道题,大致为:变量i,10个线程分别对其加10次,最后结果应i为100。题目其实不难,但是由于自身很少多线程编程,所以在面试中答得不好,所以下来重新写了代码,巩固了一下多线程方面知识。
代码如下:
package test;
/**
* Created by zhanggan on 2016/1/21.
*/
public class Node {
private int i = 0;
public int getI() {
return i;
}
public synchronized void add() {
i++;
}
}
package test;
/**
* Created by zhanggan on 2016/1/21.
*/
public class ThreadTest implements Runnable {
private Node node;
public ThreadTest(Node node) {
this.node = node;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
node.add();
System.out.println(Thread.currentThread().getName() + ": " + n