传统线程互斥技术Synchronized01

来源:互联网 发布:淘宝评价完了怎么截图 编辑:程序博客网 时间:2024/05/20 14:20
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();
}
}




}
0 0
原创粉丝点击