欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

eclipse中创建maven项目

程序员文章站 2024-03-21 17:45:34
...

代码如下

package chapterTwo.synchronize;

import chapterTwo.synchronizeUtils.Service;
import chapterTwo.synchronizeUtils.*;

public class Run {
    public static void main(String[] args){
        Service service = new Service();
        ThreadA threadA = new ThreadA(service);
        threadA.setName("A");
        threadA.start();
        ThreadB ThreadB = new ThreadB(service);
        ThreadB.setName("B");
        ThreadB.start();
        ThreadC ThreadC = new ThreadC(service);
        ThreadC.setName("C");
        ThreadC.start();

    }
}

----------

package chapterTwo.synchronizeUtils;

public class ThreadA extends Thread {
    private Service service;
    public ThreadA(Service service) {
        super();
        this.service = service;
    }

    @Override
    public void run(){
        super.run();
        service.printA();
    }
}
-----------
package chapterTwo.synchronizeUtils;

public class ThreadB extends Thread {
    private Service service;
    public ThreadB(Service service) {
        super();
        this.service = service;
    }

    @Override
    public void run(){
        super.run();
        service.printB();
    }
}

----------
package chapterTwo.synchronizeUtils;

public class ThreadC extends Thread {
    private Service service;
    public ThreadC(Service service) {
        super();
        this.service = service;
    }

    @Override
    public void run(){
        super.run();
        service.printC();
    }
}
------------
package chapterTwo.synchronizeUtils;

public class Service {
    //Service类锁
    synchronized public static void printA(){
        try {
            System.out.println("线程:" + Thread.currentThread().getName() + ",进入printA方法。");
            Thread.sleep(3000);
            System.out.println("线程:" + Thread.currentThread().getName() + ",离开printA方法。");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    //Service类锁 ,同一个类的类锁方法与类锁方法同步
    synchronized public static void printB(){
        try {
            System.out.println("线程:" + Thread.currentThread().getName() + ",进入printB方法。");
            Thread.sleep(3000);
            System.out.println("线程:" + Thread.currentThread().getName() + ",离开printB方法。");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    //对象锁,与类锁不同步,即这个类的对象调用这个类的类锁方法与对象锁方法不同步
    synchronized public void printC(){ 
        try {
            System.out.println("线程:" + Thread.currentThread().getName() + ",进入printC方法。");
            Thread.sleep(3000);
            System.out.println("线程:" + Thread.currentThread().getName() + ",离开printC方法。");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


}

结果:

eclipse中创建maven项目

总结:

  • 同一个类的类锁方法及代码块是同步的。
  • 同一个类的对象锁和类锁方法及代码块是不同步的。
相关标签: synchronized