synchronized Thread

来源:互联网 发布:js定义匿名函数 编辑:程序博客网 时间:2024/05/21 00:53

public class ThreadTest implements Runnable {

int tackets = 100;

String str = new String(""screen.width/2)this.style.width=screen.width/2;" border=0>;

public void run() {

if (str.equals("method"screen.width/2)this.style.width=screen.width/2;" border=0>) {

while (true) {

                                  //synchronized (str){} -----------1信号量为str

synchronized (this) {

if (tackets > 0) {

try {

Thread.sleep(10);

} catch (InterruptedException e) {

throw new RuntimeException(e);

}

//synchronized(this){}

   System.out.println(Thread.currentThread().getName()+" "+ "代码块" + " "+tackets--);

}

}

}

} else {

share();

}

}

public synchronized void share() {------------2//信号量为this

if (tackets > 0) {

try {

         Thread.sleep(10);

} catch (InterruptedException e) {

throw new RuntimeException(e);

}

//synchronized(str){}

   System.out.println(Thread.currentThread().getName() + " "+"方法"+ " "+tackets--);

}

}

public static void main(String[] args) {

ThreadTest tt = new ThreadTest();

Thread T0 = new Thread(tt);

T0.start();//thread 1

try {

Thread.sleep(100);

} catch (InterruptedException e) {

e.printStackTrace();

}

//-------------------

tt.str = new String("method"screen.width/2)this.style.width=screen.width/2;" border=0>;//修改变量。

//-------------------

Thread T1 = new Thread(tt);

T1.start();//thread 2

Thread T2 = new Thread(tt);

T2.start();//thread 3

try {

Thread.sleep(100);

} catch (InterruptedException e) {

e.printStackTrace();

}

//-------------------

tt.str = new String(" "screen.width/2)this.style.width=screen.width/2;" border=0>;//修改变量。

//-------------------

Thread T3 = new Thread(tt);

T3.start();//thread 2//thread 4

}

}

总结 :

   1 sleep()继承Thread类,而wait()继承 Object, sleep()只能用在非同步控制方法中,同样,只能在同步线程中使用wait(),notify(),allnotify();调用wait(),notify(),allnotify()方法的线程,在调用之前,必须获得这个对象的锁(信号量,监视器(对象唯一的标识位,值“ 0 ”或者“ 1 ”))

  2 synchronized 可以用来修饰一个对象,代码1处,也可以修饰一个方法,或者是方法中的一部份(临界区),代码2处

synchronized(任意的对象){ }          //修饰代码块时,监视器为-----任意的对象

public synchronized void share()      //修饰方法时,监视器为-----this

其中,synchronized(){ } 被用来指定某个代码块时,这个对象的锁,被用来对花括号中的代码进行同步控制。

 3 对于某个对象的所有的synchronized方法,如代码中既有同步代码块,又有同步方法,那么他们都共享一个对象锁,这样才能防止多个线程同时访问对象所在的内存。

 4 死锁,就是同时在等信号量的出现的情况