1. 程式人生 > >Synchronized及其引數一些理解

Synchronized及其引數一些理解

package com.ht.thread;

public class Ticket2 implements Runnable{

	TicketDemo ticket;
	public Ticket2(TicketDemo ticket){
		this.ticket = ticket;
	}
	public void run(){
		ticket.getOneTicket();
	}
	public static void main(String[] args) throws InterruptedException {
		int count = 100;
		TicketDemo ticket = new TicketDemo(count);
		Thread[] ts = new Thread[count];
		for(int i=0;i<count;i++){
			Ticket2 t = new Ticket2(ticket);
			ts[i] = new Thread(t);
			ts[i].start();
		}
		for(int i=0;i<count;i++){
			ts[i].join();
		}
		System.out.println(ticket.count);
	}
}

class TicketDemo{
	
	public TicketDemo(int count){
		this.count = count;
	}
	int count;
	String str = "";//有效
	Tiger1 tiger = new Tiger1();//有效
	void getOneTicket(){
		String str2 = "";//有效
		String str3 = new String("");//無效
		Integer i1 = 88;//有效
		Integer i2 = new Integer(88);//無效
		try {
			Thread.sleep(190);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		synchronized (i2) {
			-- count;
		}
			
		
	}
}
class Tiger1{
	public Tiger1() {
		System.out.println("pppppppppppppp");
	}
}

輸出:

pppppppppppppp
9

得出的結論是:

鎖成員變數必定可以成功,因為所有執行緒公用一份成員變數

鎖run()方法中間的變數,不能是new出來的新的物件。