• java 多线程 资源共享


    在控制资源共享的语句外,加入 synchronized(this)  (this也可用private Object o 对象),来进行写锁保护 
    class M
    {
    private static M m = new M();
    public static M getInstance()
    {
    return m;
    }
    public void check(int i)
    {
    System.out.println("I'm waiting, Thread "+i);
    synchronized(this)
    {
    System.out.println("I'm processing, Thread "+i);
    try {
    Thread.sleep(5000l);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }
    synchronized void method(int i)
    {
    System.out.println("I'm in synchronized function "+ i);
    try {
    Thread.sleep(1000l);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }
    public class CheckCloneable implements Runnable
    {
    private int i;
    private boolean test_function_syn;
    CheckCloneable(int i,boolean test_function_syn)
    {
    this.i = i;
    this.test_function_syn = test_function_syn;
    }
    public void run()
    {
    M m = M.getInstance();
    if(!test_function_syn)
    {
    m.check(i);
    }
    else
    {
    System.out.println("I'm waiting synchronized function "+ i);
    m.method(i);
    }
    }
    public static void main(String[] args)
    {
    for(int i=0;i<5;i++)
    {
    System.out.println("main");
    CheckCloneable c = new CheckCloneable(i,true);
    Thread t = new Thread(c);
    t.start();
    }
    }
    }
  • 相关阅读:
    Hadoop安装配置(ubuntu-12.04.2-server-amd64)
    初识hadoop
    mybatis多表关联配置
    mybatis的详解
    SpringMVC学习笔记
    spring注解
    web filter用spring注入对象
    luence全文检索(数据库检索)
    C++ inline 函数
    Ubuntu16.04 QT5编译出现cannot find -lGL和collect2:error:ld r
  • 原文地址:https://www.cnblogs.com/kevinge/p/1800433.html
Copyright © 2020-2023  润新知