zoukankan      html  css  js  c++  java
  • 关于线程锁作用对象的基础知识!

    线程不同步,欲使用 synchronized 来同步锁,必须保证线程作用的是同一个对象!否则锁不起作用!

    简单demo例子:

    方式一:

    package com.test;
    
    public class Test10{
    
    	//==单例对象!(对象不唯一,synchronized不起作用!)====================
    	private Test10(){};//构造方法私有化
    	private static Test10 t10;//对象私有化
    	public static Test10 getOnly(){
    		if(t10 == null){
    			t10 = new Test10();
    		}
    		return t10;
    	}
    	//==多线程=======================
    	public void init1(){
    		new Thread(new Runnable() {
    			public void run() {
    				getOnly().con("生产");
    			}
    		}).start();
    	}
    	public void init2(){
    		new Thread(new Runnable() {
    			public void run() {
    				getOnly().con("消费");
    			}
    		}).start();
    	}
    	//==线程间竞争的方法================
    	public synchronized void con(String con){
    		for(int i=0;i<1000;i++){
    			System.out.println(con+i);
    		}
    	}
    	
    	public static void main(String[] args) {
    		getOnly().init1();
    		getOnly().init2();
    	}
    }
    

    方式二:

    package com.test;
    
    public class Test11 {
    	
    	//==一个方法内多个线程=======================
    	public void init1(){
    		
    		//只有一个对象!
    		final Test11 t11 = new Test11();
    		
    		new Thread(new Runnable() {
    			public void run() {
    				t11.con("生产");
    			}
    		}).start();
    		new Thread(new Runnable() {
    			public void run() {
    				t11.con("消费");
    			}
    		}).start();
    	}
    	
    	//==线程间竞争的方法================
    	public synchronized void con(String con){
    		for(int i=0;i<100;i++){
    			System.out.println(con+i);
    		}
    	}
    }
    class Testxx{
    	
    	public static void main(String[] args) {
    		
    		final Test11 t11 = new Test11();
    		t11.init1();
    		
    	}
    	
    }
    

      

  • 相关阅读:
    情报分析技术领域主要研究人员
    《Dynamic Topic Detection and Tracking: A Comparison of HDP, C-Word, and Cocitation Methods》笔记
    Adobe Acrobat 9 Pro 注册码
    文件访问被拒绝 需要管理员权限
    批量文件重命名工具-极力推荐 advanced renamer
    Discuz登录慢、退出也慢的原因?
    一些需要阅读的论文
    webview上传图片
    自定义圆形图片
    touch ImageView
  • 原文地址:https://www.cnblogs.com/xuehuashanghe/p/9041938.html
Copyright © 2011-2022 走看看