1.使用synchronized代码块及其原理
2.使用synchronized方法
3.分析静态方法所使用的同步监视对象是什么?
4.Wait与notify实现线程间的通信
(1)用面试宝典中的子线程循环10次和主线程循环5次,两者交替运行50的例子进行讲解。
(2)为了观察程序的运行结果,可以在eclipse中设置运行对话框,让结果重定向到一个文本文件,然后用UE去查看该文本文件中的特殊的行号处是否正好对应了线程的切换点。
经验:要用到共同数据(包括同步锁)的若干个方法应该归在同一个类身上,这种设计正好体现了高类聚和程序的健壮性。//重点理解这句话实例
1:使用同步方法,或者同步代码块 实现方法的互斥
public class ThreadDemo_01{
public static void main(String[] args) {
final Outputer output=new Outputer();
new Thread(new Runnable() {
@Override
public void run() {
while(true){
output.output("xiaoming");
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while(true){
output.output2("xiaohong");
}
}
}).start();
}
static class Outputer{
public void output(String name){
synchronized (this) {
int length=name.length();
for (int i = 0; i < length; i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
}
/*
静态方法的默认锁是:类的字节码
普通方法的默认锁是:this
*/
public synchronized static void output2(String name){
int length=name.length();
for (int i = 0; i < length; i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
}
}
实例2:使用同步方法,或者同步代码块 实现方法的互斥
使用 信号量,wait与notify方法实现线程间的通信,同步
public class TraditionalThreadCommunication {
public static void main(String[] args) {
final Business business = new Business();
new Thread(
new Runnable() {
@Override
public void run() {
for(int i=1;i<=50;i++){
business.sub(i);
}
}
}
).start();
for(int i=1;i<=50;i++){
business.main(i);
}
}
}
class Business {
private boolean bShouldSub = true;
public synchronized void sub(int i){
while(!bShouldSub){ //此处使用while比使用if好,防止线程的虚假唤醒(几率小,但是也要考虑),要使用while更安全
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int j=1;j<=10;j++){
System.out.println("sub thread sequence of " + j + ",loop of " + i);
}
bShouldSub = false;
this.notify();
}
public synchronized void main(int i){
while(bShouldSub){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int j=1;j<=100;j++){
System.out.println("main thread sequence of " + j + ",loop of " + i);
}
bShouldSub = true;
this.notify();
}
}
199

被折叠的 条评论
为什么被折叠?



