线程同步 synchronized关键字使用

来源:互联网 发布:安装双系统win7和linux 编辑:程序博客网 时间:2024/05/18 18:42
package com.yys.thread;/** * Created by yys on 2017/9/25. */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.start();        t2.start();    }    @Override    public void run() {        timer.add(Thread.currentThread().getName());    }}class Timer{    private static int num = 0;    //synchronized 关键字锁定当前对象 只有当前对象执行完成后释放锁 其他线程才能访问    //此例子中 t1 执行时候方法内部所有对象是锁定的只有t1执行完后释放锁喉 t2才能继续执行    //如果不加锁输出结果是 Thread-0, 你是第2个使用timer的线程 Thread-1, 你是第2个使用timer的线程    //加锁输出结果是 Thread-0, 你是第1个使用timer的线程 Thread-1, 你是第2个使用timer的线程    public synchronized void add(String name){        try {            num ++;            Thread.sleep(1);        } catch (InterruptedException e) {            e.printStackTrace();        }        System.out.println(name + ", 你是第"+num+"个使用timer的线程");    }}
原创粉丝点击