Java多线程之syncronized(一)

来源:互联网 发布:iphone打击垫软件 编辑:程序博客网 时间:2024/06/05 07:23

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

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


}


}


原创粉丝点击