由于cup无规律的切换线程,导致的安全问题可以用同步技术来解决。这里要介绍synchronized关键字。其后面括号里放的是任意创建对象的对象名。
class Ticket implements Runnable {
int num = 200;
Object o = new Object();
public void run() {
while (true) {
synchronized (o) { //此处进行同步
if (num > 0) {
System.out.println(Thread.currentThread().getName() + "----" + num--);
}
else {
break;
}
} //此处进行释放
}
}
}
class Demo {
public static void main(String[] args) {
Ticket t = new Ticket();
Thread tt = new Thread(t);
Thread ttt = new Thread(t);
tt.start();
ttt.start();
}
}