public class SynDemo01 {
public static void main(String[] args) {
//真实角色
WebTicket web=new WebTicket();
//代理
Thread Tom=new Thread(web, "张三");
Thread Jess=new Thread(web, "李四");
Thread Chois=new Thread(web, "王二");
//启动线程
Tom.start();
Jess.start();
Chois.start();
}
}
//线程安全的类
class WebTicket implements Runnable{
private int num=15;
private boolean flag=true;
@Override
public void run() {
while(flag){
test3();
}
}
//线程不安全,锁定资源不正确
public void test5(){
synchronized((Integer)num){//同步块
if (num<=0) {
flag=false;//跳出循环
return;
}
try {
Thread.sleep(500);//模拟延时
} catch (Exception e) {
// TODO: handle exception
}
System.out.println(Thread.currentThread().getName()+"抢到了--》"+num--);
}
}
//锁定范围不正确
public void test4(){
synchronized(this){//同步块
if (num<=0) {
flag=false;//跳出循环
return;
}
}
try {
Thread.sleep(500);//模拟延时
} catch (Exception e) {
// TODO: handle exception
}
System.out.println(Thread.currentThread().getName()+"抢到了--》"+num--);
}
//线程安全,锁定正确
public void test3(){
synchronized(this){//同步块
if (num<=0) {
flag=false;//跳出循环
return;
}
try {
Thread.sleep(500);//模拟延时
} catch (Exception e) {
// TODO: handle exception
}
System.out.println(Thread.currentThread().getName()+"抢到了--》"+num--);
}
}
//线程安全,锁定正确
public synchronized void test2(){
if (num<=0) {
flag=false;//跳出循环
return;
}
try {
Thread.sleep(500);//模拟延时
} catch (Exception e) {
// TODO: handle exception
}
System.out.println(Thread.currentThread().getName()+"抢到了--》"+num--);
}
//线程不安全
public void test1(){
if (num<=0) {
flag=false;//跳出循环
}
try {
Thread.sleep(500);
} catch (Exception e) {
// TODO: handle exception
}
System.out.println(Thread.currentThread().getName()+"抢到了--》"+num--);
}
}
[线程]——线程同步与锁定1_synchronized
最新推荐文章于 2022-10-13 16:49:32 发布