package testlock;
//卖票程序的同步代码块实现示例
class Ticket implements Runnable {
// 定义30张票
private static int tickets = 30;
public void run() {
while (true) {
sellTicket();
}
}
private synchronized void sellTicket() {
if (tickets > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在出售第" + (tickets--) + "张票 ");
}
}
}
public class TicketDemo {
public static void main(String[] args) throws InterruptedException {
// 通过Thread类创建线程对象,并将Runnable接口的子类对象作为Thread类的构造函数的参数进行传递。
Ticket ticket = new Ticket();
Thread t1 = new Thread(ticket, "线程1");
Thread t2 = new Thread(ticket, "线程2");
Thread t3 = new Thread(ticket, "线程3");
Thread t4 = new Thread(ticket, "线程3");
// 调用线程对象的start方法开启线程。
t1.start();
t2.start();
t3.start();
t4.start();
// t1.sleep(10000);//线程霸道谁也不让,自己单独享用在时间内
// t1.setPriority(7);// 设置优先级别,默认5
}
}
//卖票程序的同步代码块实现示例
class Ticket implements Runnable {
// 定义30张票
private static int tickets = 30;
public void run() {
while (true) {
sellTicket();
}
}
private synchronized void sellTicket() {
if (tickets > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在出售第" + (tickets--) + "张票 ");
}
}
}
public class TicketDemo {
public static void main(String[] args) throws InterruptedException {
// 通过Thread类创建线程对象,并将Runnable接口的子类对象作为Thread类的构造函数的参数进行传递。
Ticket ticket = new Ticket();
Thread t1 = new Thread(ticket, "线程1");
Thread t2 = new Thread(ticket, "线程2");
Thread t3 = new Thread(ticket, "线程3");
Thread t4 = new Thread(ticket, "线程3");
// 调用线程对象的start方法开启线程。
t1.start();
t2.start();
t3.start();
t4.start();
// t1.sleep(10000);//线程霸道谁也不让,自己单独享用在时间内
// t1.setPriority(7);// 设置优先级别,默认5
}
}