• 关于线程锁作用对象的基础知识!


    线程不同步,欲使用 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();
    		
    	}
    	
    }
    

      

  • 相关阅读:
    fatal error: bits/c++config.h: No such file or directory
    linux 下Beyond Compare 安装
    TD 加载界面实现
    JPA 如何实现 insert ignore
    jsonp 未实现跨域的原因?
    Linux 常用命令
    rancher server偶发504问题排查
    docker清理none image
    docker构建权限问题
    docker containers logs clean
  • 原文地址:https://www.cnblogs.com/xuehuashanghe/p/9041938.html
Copyright © 2020-2023  润新知