传统线程互斥技术Synchronized 02

package cn.itcast.heima2;


public class ThaditionalThreadSynchronized {


public static void main(String[] args) {
new ThaditionalThreadSynchronized().init();


}
private void init(){
final OutPuter outputer = new OutPuter();
//在静态方法中不能new内部内的实例对象
new Thread(new Runnable(){
@Override
public void run() {
while(true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
outputer.outPut("zhangxiaoxiang");
}
}

}).start();

new Thread(new Runnable(){
@Override
public void run() {
while(true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
outputer.outPut2("lihongming");
}
}

}).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();
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();
}
}




}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页