您的位置:首页 > 其它

同步方法的几种常见写法

2015-12-10 11:11 295 查看
同步的位置分三种:(1)静态方法的同步,(2)非静态方法的同步,(3)代码块的同步

静态方法的同步:

public static synchronized void check(){
int i =0;
while(i>100){
try {
System.err.println("栈满了");
SynchronizedStack.class.wait();// 等待,直到有数据出栈
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}
}
i++;
System.out.println("正在使用第"+i+"个");

}


非静态方法的同步

public synchronized char pop() {
while (index == 0) {
try {
System.err.println("栈空了");
this.wait();// 等待,直到有数据出栈
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}
}
index--; // 指针向下移动
char ch = data[index];
this.notify(); // 通知其它线程把数据入栈
return ch;
}


代码块的同步:(1)

 

public void check1(int i){
synchronized(this){
while(i>100){
try {
System.err.println("栈满了");
SynchronizedStack.class.wait();// 等待,直到有数据出栈
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}

}
i++;
System.out.println("正在使用第"+i+"个");
SynchronizedStack.class.notify();
}

}
同步代码块:(2)
</pre><pre name="code" class="java">public void check2(int i){
synchronized(SynchronizedStack.class){
while(i>100){
try {
System.err.println("栈满了");
SynchronizedStack.class.wait();// 等待,直到有数据出栈
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}

}
i++;
System.out.println("正在使用第"+i+"个");
SynchronizedStack.class.notify();
}

}


同步代码块(3)

public  static void check2(int i){
synchronized(SynchronizedStack.class){
while(i>100){
try {
System.err.println("栈满了");
SynchronizedStack.class.wait();// 等待,直到有数据出栈
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}

}
i++;
System.out.println("正在使用第"+i+"个");
SynchronizedStack.class.notify();
}

}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: