3.25 - 3.26 Java学习总结
程序员文章站
2022-07-10 21:21:19
...
多线程
多线程优先级
多线程同步
本来代码照着敲的,结果一运行电脑直接 “起飞” 并且结果也不一样,然后自己加了个else进去(结果还是不同)。
package shuzu.ppy.oo;
public class ThreadSafeTest implements Runnable{
int num = 10;
public void run() {
while(true) {
if(num > 0) {
try {
Thread.sleep(100);
}catch(Exception e){
e.printStackTrace();
}
System.out.println("tickes: " + num--);
}
else {
break;
}
}
}
public static void main(String[] args) {
ThreadSafeTest t = new ThreadSafeTest();
Thread tA = new Thread(t);
Thread tB = new Thread(t);
Thread tC = new Thread(t);
Thread tD = new Thread(t);
tA.start();
//System.out.println("\n-----分隔线-----\n");
tB.start();
//System.out.println("\n-----分隔线-----\n");
tC.start();
//System.out.println("\n-----分隔线-----\n");
tD.start();
}
}
tickes: 10
tickes: 10
tickes: 8
tickes: 9
tickes: 7
tickes: 7
tickes: 7
tickes: 7
tickes: 6
tickes: 6
tickes: 6
tickes: 6
tickes: 5
tickes: 4
tickes: 4
tickes: 3
tickes: 1
tickes: 2
tickes: 2
tickes: 2