日期:2020/1/15
功能:理解java中的两种进程同步方法
IDE:Intellij IDEA
第一种方法
使用synchronized关键字:在需要访问的类中的方法声明(共享资源)前加上synchronized关键字,这样,当多进程调用该方法时,如果某个进程已经在使用了,其他进程必须等待
package testDemo;
class OutTest{
public static synchronized void print(char c){
for(int i=0;i<4;i++){
System.out.println(c);
try {
Thread.sleep(1000);
}catch (InterruptedException e){
System.out.println(e.getClass());;
}
}
}
}
public class ThreadTest extends Thread{
private char ch;
public ThreadTest(char ch){
this.ch = ch;
}
public void run(){
OutTest.print(ch);
}
public static void main(String[] args){
ThreadTest threadTest = new ThreadTest('A');
ThreadTest threadTest1 = new ThreadTest('B');
threadTest.start();
threadTest1.start();
}
}
第二种方法
当我们不能得到某些方法的源代码时候,比如上面的OutTets.print()方法,这时候我们就不可以在声明前面加上synchronized关键字,所以,我们可以使用“同步代码块”。格式如下:synchronized(object){…},object就是我们需要访问的资源,谁访问了object,谁就拥有控制权
package testDemo;
class OutTest{
public void print(char c){
for(int i=0;i<4;i++){
System.out.println(c);
try {
Thread.sleep(1000);
}catch (InterruptedException e){
System.out.println(e.getClass());;
}
}
}
}
public class ThreadTest extends Thread{
private char ch;
public ThreadTest(char ch){
this.ch = ch;
}
public void run(){
OutTest outTest = new OutTest();
synchronized (outTest){
outTest.print(ch);
}
}
public static void main(String[] args){
ThreadTest threadTest = new ThreadTest('A');
ThreadTest threadTest1 = new ThreadTest('B');
threadTest.start();
threadTest1.start();
}
}