Java synchronized

public class MyTest {

	public void m4tab() {
		// TODO Auto-generated method stub
		synchronized (this) {
			for (int i = 0; i < 5; i++) {
				System.out.println(Thread.currentThread().getName()
						+ " synchronized " + i);
			}
		}
	}

	public void m4t1() {
		int i = 5;
		while (i-- > 0) {
			System.out.println(Thread.currentThread().getName() + " : " + i);
			try {
				Thread.sleep(500);
			} catch (InterruptedException ie) {
			}
		}
	}

	public void m4t2() {
		int i = 5;
		synchronized (this) {
			while (i-- > 0) {
				System.out
						.println(Thread.currentThread().getName() + " : " + i);
				try {
					Thread.sleep(500);
				} catch (InterruptedException ie) {
				}
			}
		}
	}

	public void m4t3() {
		int i = 5;
		synchronized (this) {
			while (i-- > 0) {
				System.out
						.println(Thread.currentThread().getName() + " : " + i);
				try {
					Thread.sleep(500);
				} catch (InterruptedException ie) {
				}
			}
		}
	}

	public static void main(String[] args) {

		MyTest mTest = new MyTest();
		Thread ta = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				mTest.m4tab();
			}
		}, "A");

		Thread tb = new Thread(new Runnable() {
			public void run() {
				mTest.m4tab();
			}
		}, "B");

		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				mTest.m4t1();
			}
		}, "T1");

		Thread t2 = new Thread(new Runnable() {
			public void run() {
				mTest.m4t2();
			}
		}, "T2");

		Thread t3 = new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				mTest.m4t3();
			}
		}, "T3");
		ta.start();
		tb.start();
		t1.start();
		t2.start();
		t3.start();
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章