[Java] Thread-04 线程同步 TestSync / TestDeadLock / TT

public class TestSync implements Runnable {
    Timer timer = new Timer();

    public static void main(String[] args) {
        TestSync test = new TestSync();
        Thread t1 = new Thread(test);
        Thread t2 = new Thread(test);
        t1.setName("t1");
        t2.setName("t2");
        t1.start();
        t2.start();
    }

    public void run() {
        timer.add(Thread.currentThread().getName());
    }
}

class Timer {
    private static int num = 0;

    public synchronized void add(String name) { // 锁定当前对象资源
        // synchronized (this) {
        num++;
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
        }
        System.out.println(name + ", 你是第" + num + "个使用timer的线程");
        // }
    }
}

public class TestDeadLock implements Runnable {
    public int flag = 1;
    static Object o1 = new Object(), o2 = new Object();

    public void run() {
        System.out.println("flag=" + flag);
        if (flag == 1) {
            synchronized (o1) {
                try {
                    Thread.sleep(500);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                synchronized (o2) {
                    System.out.println("1");
                }
            }
        }
        if (flag == 0) {
            synchronized (o2) {
                try {
                    Thread.sleep(500);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                synchronized (o1) {
                    System.out.println("0");
                }
            }
        }
    }

    public static void main(String[] args) {
        TestDeadLock td1 = new TestDeadLock();
        TestDeadLock td2 = new TestDeadLock();
        td1.flag = 1;
        td2.flag = 0;
        Thread t1 = new Thread(td1);
        Thread t2 = new Thread(td2);
        t1.start();
        t2.start();

    }
}
--仅仅是锁定了整个对象的这个方法而已。其他方法还是可以被调用的
public class TT implements Runnable {
    int b = 100;
    
    public synchronized void m1() throws Exception{ // 仅仅是锁定了整个对象的这个方法而已。其他方法还是可以被调用的
        //Thread.sleep(2000); // synchronized (this) { // 锁定当前方法,仅仅代表 与 不注释的写法是相同的
        b = 1000;
        Thread.sleep(5000);
        System.out.println("b = " + b);
    }
    
    public synchronized void m2() throws Exception {  // 已经被锁,现在锁不住了,只能等待
        Thread.sleep(2500);
        b = 2000;
    }
    
    public void run() {
        try {
            m1();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) throws Exception {
        TT tt = new TT();
        Thread t = new Thread(tt);
        t.start();
        
        tt.m2();
        System.out.println(tt.b);
    }
}

posted @ 2013-12-08 16:42  小尼人00  阅读(178)  评论(0编辑  收藏  举报