您的位置:首页 > 其它

线程学习之--传统线程互斥

2012-10-13 11:49 183 查看
//线程同步

publicstaticvoidmain(String[] args) {

newSync().show();

}

publicvoidshow(){

final Infoinfo=new Info();

//创建一个线程

newThread(new Runnable(){

publicvoidrun() {

while(true){

try {

Thread.sleep(10);

} catch(InterruptedException e) {

e.printStackTrace();

}

info.outname1("wangyong");

}

}

}).start();

//在创建一个线程

newThread(new Runnable(){

publicvoidrun() {

while(true){

try {

Thread.sleep(10);

} catch(InterruptedException e) {

e.printStackTrace();

}

info.outname1("zhangsan");

}

}

}).start();

}

classInfo{

publicvoidoutname1(String name){

intlen=name.length();

for(inti=0;i<len;i++){

System.out.print(name.charAt(i));

}

System.out.println();

}

}

}

以上的实例可以看出,线程不同步。

该如何修改呢?

packagedemo;

publicclass Sync{

/**

*@paramargs

*/

//线程同步

publicstaticvoidmain(String[] args) {

newSync().show();

}

publicvoidshow(){

final Infoinfo=new Info();

//创建一个线程

newThread(new Runnable(){

publicvoidrun() {

while(true){

try {

Thread.sleep(10);

} catch(InterruptedException e) {

e.printStackTrace();

}

info.outname1("wangyong");

}

}

}).start();

//在创建一个线程

newThread(new Runnable(){

publicvoidrun() {

while(true){

try {

Thread.sleep(100);

} catch(InterruptedException e) {

e.printStackTrace();

}

info.outname3("zhangsan");

}

}

}).start();

}

staticclassInfo{

//方法一

publicvoidoutname1(String name){

intlen=name.length();

synchronized(Info.class){

for(inti=0;i<len;i++){

System.out.print(name.charAt(i));

}

System.out.println();

}

}

//方法二

publicsynchronizedvoidoutname2(String name){

intlen=name.length();

for(inti=0;i<len;i++){

System.out.print(name.charAt(i));

}

System.out.println();

}

//方法二

publicstaticsynchronizedvoidoutname3(String
name){

intlen=name.length();

for(inti=0;i<len;i++){

System.out.print(name.charAt(i));

}

System.out.println();

}

}

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