public class Windows1 implements Runnable {
private int ticket=100;
// 为线程创建了一个对象锁
Object object=new Object();
@Override
public void run() {
// 若写在这里则一个线程一把锁不具备公用行 Object object=new Object();
while (true){
synchronized (object){//或synchronized (this)当前对象来充当对象锁
// 包起来操作共享数据的代码,若把while包进来,相当于一个进程进来一直满足while便一直执行
if (ticket>0){
try {
// 确保线程能挤进来的概率
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"出售"+ticket+"号票");
ticket--;
}
else
break;
}
}
}
}
class WindowsTest1{
public static void main(String[] args) {
// 只建立了一个对象所以也只有一个对象锁
Windows1 windows1=new Windows1();
Thread thread1=new Thread(windows1);
Thread thread2=new Thread(windows1);
Thread thread3=new Thread(windows1);
thread1.setName("窗口1");
thread2.setName("窗口2");
thread3.setName("窗口3");
thread1.start();
thread2.start();
thread3.start();
}
}
synchronized的应用
最新推荐文章于 2023-04-23 19:35:06 发布