synchronized實現多線程 java代碼示例

多線程代碼示例

//自定義類Multithreading    實現  Runnable
public class Multithreading implements Runnable{
	public int i=1;
	public Multithreading(int i) {
		this.i = i;
		System.out.println("入參i:"+i);
	}
	@Override
	public void run() {
		try {
		System.out.println("輸出1");
		Thread.sleep(10000);
		//關鍵字synchronized可以保證在同一時刻,只有一個線程可以執行某個方法或某個代碼塊
		synchronized (Multithreading.class) {
			System.out.println("輸出2");
			Thread.sleep(10000);
			if(CheckFile(i)){
				System.out.println("i-奇數");
			}else{
				System.out.println("i-偶數");
			}
			++i;
			System.out.println("++i:"+i);
		}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	private boolean CheckFile(int i){
		boolean tag=false;
		if(i%2 == 1){//i-奇數
			tag = true;
		}else {//i-偶數
			tag = false;
		}
		System.out.println("tag:"+tag);
		return tag;
	}
}
``
//調用測試
public void test() {
	new Thread(new Multithreading(1)).start();
	new Thread(new Multithreading(2)).start();
	new Thread(new Multithreading(3)).start();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章