实现Runnable接口创建线程,并验证同步函数this锁--存疑

来源:互联网 发布:spss如何将数据分组 编辑:程序博客网 时间:2024/06/16 01:23

实现Runnable接口创建线程,并验证同步函数this锁–存疑

存疑:调用发现,线程t1,t2都没有消亡,执行结果只有t1线程。

package javaTest.xiancheng.Test;/* * 判断同步函数的锁是this锁 */public class ThisLock implements Runnable{    private int num=100;    public boolean flag=true;    Object obj=new Object();    public void run(){        //当flag为true时执行同步代码块        if(flag){            //将同步代码块的锁设置为this锁            synchronized (this) {//由obj换成this与同步函数对比                while(num>0){                    try {                        //手动添加sleep模拟异常                        Thread.sleep(10);                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                    System.out.println(Thread.currentThread().getName()+num--);                }            }        }        //当flag为false时执行同步函数        else{            //调用同步过函数            synfunction();        }       }    //同步函数    public synchronized void synfunction(){//同步函数的锁是this锁        while(num>0){            try {                //手动添加sleep模拟异常                Thread.sleep(10);            } catch (InterruptedException e) {                e.printStackTrace();            }            System.out.println(Thread.currentThread().getName()+num--);        }    }}--------------------------------------------------package javaTest.xiancheng.Test;public class Test_ThisLock {/* * 判断同步函数的锁是this锁的测试类 */    public static void main(String[] args) {        ThisLock th=new ThisLock();        Thread t1=new Thread(th,"线程1..");        Thread t2=new Thread(th,"线程2..");        t1.start();        System.out.println("线1 "+t1.isAlive());        try {            Thread.sleep(0);        } catch (InterruptedException e) {            e.printStackTrace();        }        th.flag=false;        t2.start();        System.out.println("线2 "+t2.isAlive());    }}
0 0
原创粉丝点击