Java多线程之syncronized(一)

为了理解线程为什么需要同步,我举下面的一个例子来说明:

package three.day.thread;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;


public class ThreadTs2 {


public static void main(String[] args) throws FileNotFoundException {
//final OutputStream file = new FileOutputStream("syncronizedClass.txt");
//System.setOut(new PrintStream(file));//原来System.out内容是输出到控制,现在输出到工程目录下的文件,文件路径相对路径,是相对工程目录
new Thread(new Runnable(){
private String msg = "lirizhong";
@Override
public void run(){
while(true){
/*synchronized (file ThreadTs2.class)*/ {//这里先把同步代码块注释
for (int i = 0; i < msg.length(); i++) {
System.out.print(msg.charAt(i));
}
System.out.println("");
}
}

}
}).start();
new Thread(new Runnable(){
private String msg = "zhonghuarenmingongheguo";
@Override
public void run(){
while(true){
/*synchronized (fileThreadTs2.class )*/ {//这里先把同步代码块注释
for (int i = 0; i < msg.length(); i++) {
System.out.print(msg.charAt(i));
}
System.out.println("");
}
}
}
}).start();


}


}

}


代码运行结果:

zhonghuarenmingongheguo
zhonghuarenmingongheguo
zhonghuarenmingo
lirizhong
lirizhong

................(略)


由输出结果会发现,在没有同步代码的情况下,输出的字符串是不完整的,这在很多时候是不符合我们的实际需求,我们一般都要求一个线程做完了一件事情,

另外一个线程才能做。但是在计算机中,计算机系统负责统一调度每个线程,分派每个线程一定的cpu时间,不管当前线程的任务是否执行完了,只要cpu时间

到,计算机系统就会将cpu为另外一个线程服务,所以出现输出的字符串是不完整的情况。


在jdk1.5前,解决这种问题,使用的是synchronized。

在jdk.15后,可以使用线程锁


package three.day.thread;


import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


public class ThreadTs {


public static void main(String[] args) throws FileNotFoundException {
final Lock lock = new ReentrantLock();//定义一个锁
//OutputStream file = new FileOutputStream("lock.txt");
//System.setOut(new PrintStream(file));
new Thread(new Runnable(){
private String msg = "lirizhong";
@Override
public void run(){
while(true){
lock.lock();
for(int i=0;i<msg.length();i++){
System.out.print(msg.charAt(i));
}
System.out.println("");
lock.unlock();
}

}
}).start();
new Thread(new Runnable(){
private String msg = "zhonghuarenmingongheguo";
@Override
public void run(){
while(true){
lock.lock();//在lock和unlock之间特别使用对共享资源的操作
for(int i=0;i<msg.length();i++){
System.out.print(msg.charAt(i));
}
System.out.println("");
lock.unlock();
}
}
}).start();


}


}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值