线程同步加锁问题

public class TT implements Runnable {

	int b=100;
	public synchronized void m1() throws InterruptedException{
		System.out.println("m1开始执行");
		b=1000;
		Thread.sleep(5000);
		System.out.println("m1:"+b);
	}
	public synchronized void m2() throws InterruptedException{
		
		System.out.println("m2开始执行");
		Thread.sleep(2500);
		b=2000;
		System.out.println("m2:"+b);
	}
	public void run()  {
		System.out.println("run开始执行");
		try {
			m1();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws InterruptedException {
		TT tt=new TT();
		Thread t=new Thread(tt);
		t.start();
		
		//Thread.sleep(1);
		tt.m2();
		
		System.out.println("main:"+tt.b);
	}

}

 m2开始执行
run开始执行
m2:2000
main:2000
m1开始执行
m1:1000

public class TT implements Runnable {

	int b=100;
	public synchronized void m1() throws InterruptedException{
		System.out.println("m1开始执行");
		b=1000;
		Thread.sleep(5000);
		System.out.println("m1:"+b);
	}
	public  void m2() throws InterruptedException{
		
		System.out.println("m2开始执行");
		Thread.sleep(2500);
		b=2000;
		System.out.println("m2:"+b);
	}
	public void run()  {
		System.out.println("run开始执行");
		try {
			m1();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws InterruptedException {
		TT tt=new TT();
		Thread t=new Thread(tt);
		t.start();
		
		//Thread.sleep(1);
		tt.m2();
		
		System.out.println("main:"+tt.b);
	}

}

 m2开始执行
run开始执行
m1开始执行
m2:2000
main:2000
m1:2000

你可能感兴趣的:(thread)