Java多线程之syncronized(二)

来源:互联网 发布:微信聊天数据怎么恢复 编辑:程序博客网 时间:2024/06/05 15:19
package three.day.thread.my;


public class SyncronizedTs {


public static void main(String[] args) {
Thread tt = new Thread(new ThreadTest());
tt.start();
ThreadTest t = new ThreadTest();
Thread tt1 = new Thread(t);
t.setStr("xxxxx");
tt1.start();


}


}
syncronized同步代码块有三种用法,一种是syncronized方法,一种是syncronized共享对象,一种是syncronized字节码对象



class ThreadTest implements Runnable{

private static String str = "";
private static int tickets = 10;

public void setStr(String str){
this.str = str;
}
public void run(){
//sale();
sale2();
}

public void sale2(){
synchronized(str/*implements */){
try {
while (tickets !=0) {
Thread.currentThread().sleep(1000);
System.out.println(Thread.currentThread().getName() + " "
+ tickets--);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public synchronized void sale(){
try {
while (tickets !=0) {
Thread.currentThread().sleep(1000);
System.out.println(Thread.currentThread().getName() + " "
+ tickets--);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}