1.同步代码块
继承Thread实现多线程,同步代码块实现线程安全
public class ThreadDemo2 extends Thread {
public ThreadDemo2(String name)
{ super(name);}
private static int ticketNum = 100;// 共有100张门票
@Override
public void run() {
while (true) {
synchronized (ThreadDemo2.class) {
if (ticketNum > 0) {
System.out.println(Thread.currentThread().getName() + "售卖的门票号:" + ticketNum);
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ticketNum--;
}
}
if (ticketNum <= 0) {
return;//为了减少synchronized 中代码,结束判断放在外部
}
}
}
public static void main(String[] args) {
//所有的线程共用一个锁,因为都是通过一个Ticket 对象创建的线程,因此用this作为锁
ThreadDemo2 t1 = new ThreadDemo2("窗口1");
t1.start();
ThreadDemo2 t2 = new ThreadDemo2("窗口2");
t2.start();
ThreadDemo2 t3 = new ThreadDemo2("窗口3");
t3.start();
}
}
线程安全:方法二 同步方法
//示例: 售卖100张门票,实现多个窗口售卖
//线程安全synchronized :同步代码块
// 1.实现Runna接口
public class ThreadDemo1 implements Runnable {
private static int ticketNum = 100;// 共有100张门票
@Override
public void run() {
while (true) {
buyTicket();
}
}
public synchronized void buyTicket() {
if (ticketNum > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "售卖的门票号:" + ticketNum);
ticketNum--;
}
}
public static void main(String[] args) {
//所有的线程共用一个锁,因为都是通过一个Ticket 对象创建的线程,因此用this作为锁
ThreadDemo1 thread = new ThreadDemo1();
Thread t2 = new Thread(thread);
t2.setName("窗口2");
t2.start();
Thread t3 = new Thread(thread);
t3.setName("窗口3");
t3.start();
Thread t1 = new Thread(thread);
t1.setName("窗口1");
t1.start();
}
}
实现Runnable 接口,同步方法实现线程安全
/示例: 售卖100张门票,实现多个窗口售卖
//线程安全synchronized :同步代码块
// 1.实现Runna接口
public class ThreadDemo2 extends Thread {
public ThreadDemo2(String name)
{ super(name);}
private static int ticketNum = 100;// 共有100张门票
@Override
public void run() {
while (true) {
ThreadDemo2.buyTicket();
}
}
// 同步监视器是类:静态方法
public synchronized static void buyTicket(){
if (ticketNum > 0) {
System.out.println(Thread.currentThread().getName() + "售卖的门票号:" + ticketNum);
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ticketNum--;
}
}
public static void main(String[] args) {
//所有的线程共用一个锁,因为都是通过一个Ticket 对象创建的线程,因此用this作为锁
ThreadDemo2 t1 = new ThreadDemo2("窗口1");
t1.start();
ThreadDemo2 t2 = new ThreadDemo2("窗口2");
t2.start();
ThreadDemo2 t3 = new ThreadDemo2("窗口3");
t3.start();
}}