[线程]——线程同步与锁定1_synchronized

来源:互联网 发布:大学生支教后收获数据 编辑:程序博客网 时间:2024/05/22 23:03
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;@Overridepublic 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--);}}

0 0