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();
    		
    	}
    	
    }
    

      

  • 相关阅读:
    为什么学编程?如何学编程?
    数据结构2019/05/14
    Python2与Python3的区别(2)
    数据库(第一范式,第二范式,第三范式)
    Atom常用功能插件
    Atom编辑器的安装
    PL/SQL Developer安装教程(贴图)
    安装Oracle提示:[INS-35206] 目录已在使用
    安装Oracle出现环境不满足最低要求
    Oracle 11g服务器安装详细步骤(贴图)
  • 原文地址:https://www.cnblogs.com/xuehuashanghe/p/9041938.html
Copyright © 2011-2022 走看看