传统线程互斥技术Synchronized01

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/zengquan2014/article/details/50096329
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();
}
class OutPuter{
public void outPut(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 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();
}
}




}
展开阅读全文

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