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