import cn.itcast_01.MyRunnable;
public class 同步代码块的锁及同步方法应用和锁的问题 {
public static void main(String[] args) {
MyRunnable my = new MyRunnable();
Thread t1 = new Thread(my,"窗口1");
Thread t2 = new Thread(my,"窗口2");
Thread t3 = new Thread(my,"窗口3");
t1.start();
t2.start();
t3.start();
}
}
同步代码块的锁的定义
package cn.itcast_02;
public class MyRunnable implements Runnable {
private static int ticked = 100;
private Object obj = new Object();
@Override
public void run() {
while(true) {
synchronized (obj) {
if(ticked>0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"正在出售第"+(ticked--)+"票");
}
}
}
}
}
class Dome{
}
转载请注明原文地址:https://blackberry.8miu.com/read-16943.html