您的位置:首页 > 其它

多线程互斥,用到Synchronized

2015-06-07 11:53 246 查看
package com.test;

public class TraditionalThreadSynchronized {

public static void main(String [] arge){
new TraditionalThreadSynchronized().init();
}

private void init(){
final outPuter out =new outPuter();
new Thread(new Runnable() {

public void run() {
while(true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
out.output("zhangxiaoxiang");
}

}
}).start();

new Thread(new Runnable() {

public void run() {
while(true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
out.output3("liguoming");
}

}
}).start();
}
static class outPuter{

public void output(String name){
int len = name.length();
synchronized (outPuter.class) {
for(int i = 0 ;i<len;i++){
System.out.print(name.charAt(i));
}
System.out.println();
}
}

public synchronized void output2(String name){
int len = name.length();
synchronized (this) {
for(int i = 0 ;i<len;i++){
System.out.print(name.charAt(i));
}
System.out.println();
}
}

public static synchronized void output3(String name){
int len = name.length();

for(int i = 0 ;i<len;i++){
System.out.print(name.charAt(i));
}
System.out.println();

}

}

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