其他
面试官:谈谈你对Java线程安全与不安全的理解
来源:blog.csdn.net/fuzhongmin05/article/details/59110866
如果要操作少量的数据用String 单线程操作字符串缓冲区下操作大量数据StringBuilder 多线程操作字符串缓冲区下操作大量数据StringBuffer
public class Count {
private int num;
//public void count() {
// for(int i = 1; i <= 100; i++) {
// num += i;
// }
// System.out.println(Thread.currentThread().getName() + "-" + num);
//}
public int getNum() {
return num;
}
public void increment(int i) {
num = num + i;
}
}
public class ThreadTest {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
Count count = new Count();
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
count.increment(1);
}
System.out.println(Thread.currentThread().getName() + "-" + count.getNum());
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
for(int i = 0; i < 10; i++) {
Thread thread = new Thread(runnable);
thread.start();
}
}
}
Thread-0-1660
Thread-2-2660
Thread-3-3660
Thread-1-1660
Thread-4-4882
Thread-5-5579
Thread-6-6579
Thread-7-7579
Thread-8-8579
Thread-9-9579
public class Count {
public void count() {
int number = 0;
for(int i = 0; i < 1000; i++) {
number += 1;
}
System.out.println(Thread.currentThread().getName() + "-" + number);
}
}
public class ThreadTest {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
Count count = new Count();
@Override
public void run() {
count.count();
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
for(int i = 0; i < 10; i++) {
Thread thread = new Thread(runnable);
thread.start();
}
}
}
Thread-0-1000
Thread-3-1000
Thread-4-1000
Thread-1-1000
Thread-2-1000
Thread-5-1000
Thread-6-1000
Thread-7-1000
Thread-8-1000
Thread-9-1000
public class ThreadTest {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
Count count = new Count();
for (int i = 0; i < 1000; i++) {
count.increment(1);
}
System.out.println(Thread.currentThread().getName() + "-" + count.getNum());
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
for(int i = 0; i < 10; i++) {
Thread thread = new Thread(runnable);
thread.start();
}
}
}
Thread-1-1000
Thread-3-1000
Thread-2-1000
Thread-0-1000
Thread-5-1000
Thread-4-1000
Thread-6-1000
Thread-7-1000
Thread-8-1000
Thread-9-1000
推荐阅读:
点个在看你最好看