Synchronized及其参数一些理解

来源:互联网 发布:手机突然连不上4g网络 编辑:程序博客网 时间:2024/05/16 00:59
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");}}

输出:

pppppppppppppp9

得出的结论是:

锁成员变量必定可以成功,因为所有线程公用一份成员变量

锁run()方法中间的变量,不能是new出来的新的对象。


原创粉丝点击