Java多线程并发笔记02

例子程序01

/**
 * synchronized的重入
 *
 */
public class SyncDubbo1 {
	public synchronized void method1()  {
		System.out.println("method1...");
		method2();
	}

	public synchronized void method2() {
		System.out.println("method2...");
		method3();
		
	}
	public synchronized void method3() {
		System.out.println("method3...");
	}
	
	public static void main(String[] args) {
		final SyncDubbo1 syn = new SyncDubbo1();
		Thread t1 = new Thread(new Runnable() {
			
			@Override
			public void run() {
				syn.method1();
			}
		});
		t1.start();
	}
}

示例程序02 


/**
 * synchronized的重入
 *
 */
public class SyncDubbo2 {
	
	static class Main {
		public int i = 10;
		public synchronized void operateionSup() {
			try {
				i--;
				System.out.println("Main print i = " + i);
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	static class Sub extends Main {
		public synchronized void operateionSub() {
			try {
				while(i>0) {
					i--;
					System.out.println("Sub print i = " + i);
					Thread.sleep(100);
					this.operateionSup();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	
	public static void main(String[] args) {
		Thread t1 = new Thread(new Runnable() {
			
			@Override
			public void run() {
				Sub syn = new Sub();
				syn.operateionSub();
			}
		});
		t1.start();
	}
}

示例程序03

public class SyncException {
	
	private int i = 0;
	
	public synchronized void opration(){
		while(true) {
			try {
				i++;
				Thread.sleep(200);
				
				System.out.println(Thread.currentThread().getName() + " , i = " + i);
				if(i == 10) {
					Integer.parseInt("a");
				}
			} catch (Exception e) {
				//当有异常时,处理
				System.out.println("logger.info i = "+i);
				//throw new RuntimeException();
				continue;
			}
		}
	}

	public static void main(String[] args) {
		final SyncException se = new SyncException();
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				se.opration();
			}
		},"t1");
		t.start();
	}

}

猜你喜欢

转载自blog.csdn.net/guchunchao/article/details/81611121