学习线程,自减语句在输出语句内和输出语句外不同,导致输出结果也有不同
如果在输出语句内自减,大部分输出结果都是符合预期,少部分还是会超过预期
如果在输出语句外自减,大部分输出结果都是超过预期,少部分还是会符合预期
public class TestThread implements Runnable{
static int t_num=10;
@Override
public void run() {
for (int i = 1; i < 100; i++) {
if (t_num>0){
System.out.println(Thread.currentThread().getName()+"-"+t_num--+" ");//自减语句在内部
//t_num--;自减语句在外部
}
}
}
}
class test{
public static void main(String[] args) {
TestThread tt1 = new TestThread();
TestThread tt2 = new TestThread();
TestThread tt3 = new TestThread();
Thread t1 = new Thread(tt1, "t1");
Thread t2 = new Thread(tt2, "t2");
Thread t3 = new Thread(tt3, "t3");
t1.start();
t2.start();
t3.start();
}
}
是因为什么原理
附输出结果
附输出结果
①自减语句在内部
t1-10
t3-8
t2-9
t3-6
t3-4
t3-3
t3-2
t3-1
t1-7
t2-5
②自减语句在外部
t1-10
t2-10
t2-8
t2-7
t2-6
t2-5
t2-4
t3-3
t3-2
t3-1
t1-9
t2-3
其实不管在内在外,这种写法如果是多线程保证共享资源线程安全,这两种写法都是不合适的;
作为多线程的共享资源要保证线程安全,一定要让临界区互斥。采用的方式有很多比如使用Synchronized,Lock锁,以及一些原子类(Atomic)