java同步之我见

闲来研究了一下关于java同步的内容 直接上代码

package synch;

import java.util.ArrayList;
import java.util.List;

public class Test implements Runnable {

	public static List<String> list;

	private static int k1 = 0;
	
	private static int k2 = 0;

	public void run() {

		synchronized (list) {
			try {
				
				if(Thread.currentThread().getName().equals("线程1"))
					setK1(k1 + 1);
				if(Thread.currentThread().getName().equals("线程2"))
					setK2(k2 + 1);
				
				int k =Thread.currentThread().getName().equals("线程1") ? k1 :k2;
				
				System.out.println(Thread.currentThread().getName() + "第" + k + "个线程进来了");
				Thread.sleep(1000);
				
				
			} catch (Exception e) {
			}
		}

	}

	public static void main(String[] args) throws Exception {
		Test t = new Test();

		list = new ArrayList<String>();

		for (int i = 0; i < 100; i++) {
			Thread t1 = new Thread(t, "线程1");
			t1.start();
		}
		Thread.sleep(100);
		list = new ArrayList<String>();
		for (int i = 0; i < 100; i++) {
			Thread t1 = new Thread(t, "线程2");
			t1.start();
		}
	}

	public static synchronized int getK1() {
		return k1;
	}

	public static synchronized void setK1(int k1) {
		Test.k1 = k1;
	}

	public static synchronized  int getK2() {
		return k2;
	}

	public static synchronized  void setK2(int k2) {
		Test.k2 = k2;
	}

}


先说明一下代码的大致内容两个线程组,第一组名称是线程1,第二组名称是线程2,循环线程执行run,结果如下



对象loak对象,让同步失效
package synch;

import java.util.ArrayList;
import java.util.List;

public class Test1 implements Runnable {

	public static List<String> list;

	private static int k = 0;

	public void run() {

		synchronized (list) {
			try {

				setK(k + 1);
				list = new ArrayList<String>();
				System.out.println(Thread.currentThread().getName() + "第" + k
						+ "个线程进来了");
				Thread.sleep(100);
			} catch (Exception e) {
			}
		}

	}

	public static void main(String[] args) throws Exception {
		Test1 t = new Test1();

		list = new ArrayList<String>();

		for (int i = 0; i < 100; i++) {
			Thread t1 = new Thread(t, "线程1");
			t1.start();
		}

	}

	public static synchronized int getK() {
		return k;
	}

	public static synchronized void setK(int k) {
		Test1.k = k;
	}

}

很快执行完毕,在lock对象的时候,不要改变对象的地址!!!
 

猜你喜欢

转载自zhangyulong19880411.iteye.com/blog/2202625