对Java线程安全与不安全的理解
点击上方蓝色字体,选择“标星公众号”
优质文章,第一时间送达
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
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:
https://blog.csdn.net/fuzhongmin05/article/details/59110866
评论