加锁同步等待,和使用volatile 等待数据模拟阻塞

Deadly 提交于 2020-08-08 18:31:54

环境:jdk1.8 springboot maven3.5

项目结构:

maven.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>undertowdemo</groupId>
    <artifactId>undertowdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>undertowdemo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-undertow</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </pluginRepository>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

</project>

UndertowdemoApplication.java

package undertowdemo.undertowdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

//import io.undertow.Undertow;
//import io.undertow.server.HttpHandler;
//import io.undertow.server.HttpServerExchange;
//import io.undertow.util.Headers;

@SpringBootApplication
public class UndertowdemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(UndertowdemoApplication.class, args);
//        Undertow server = Undertow.builder()
//                .addHttpListener(8080, "localhost")
//                .setHandler(new HttpHandler() {
//                    @Override
//                    public void handleRequest(final HttpServerExchange exchange) throws Exception {
//                        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
//                        exchange.getResponseSender().send("Hello World");
//                    }
//                }).build();
//        server.start();
    }

}

HelloController.java

package undertowdemo.undertowdemo.web;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.concurrent.Executors;

import javax.annotation.Resource;

import io.undertow.util.DateUtils;
import undertowdemo.undertowdemo.HelloService;


/**
 * description:
 *
 * @author: he QQ:       905845006
 * @email: 905845006@qq.com
 * @date: 2020/7/13    9:07 PM
 */
@RestController
@RequestMapping
public class HelloController {

    @Resource
    HelloService helloService;


    @RequestMapping("/all")
    public String hello(String msg){

        System.out.println("start:"+Thread.currentThread().getName()+"  +++  "+DateUtils.toDateString(new Date()));
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Executors.newSingleThreadExecutor();
        helloService.hello(msg);
        System.out.println("end:"+Thread.currentThread().getName()+"  +++  "+DateUtils.toDateString(new Date()));

//        printStack(Thread.currentThread().getStackTrace());
        return DateUtils.toDateString(new Date());
    }
    public void printStack(StackTraceElement[] stes) {
        StringBuffer sb = new StringBuffer();
        for (StackTraceElement ste : stes) {
            sb.append(ste.getClassName() + "." + ste.getMethodName() + "(" + ste.getFileName() + ":" + ste.getLineNumber() + ")\r\n");
        }
        System.out.println(sb.toString());
    }
}


HelloService.java

package undertowdemo.undertowdemo;

import org.springframework.stereotype.Service;

import java.util.Date;

import io.undertow.util.DateUtils;

/**
 * description:
 *
 * @author: he QQ:       905845006
 * @email: 905845006@qq.com
 * @date: 2020/7/22    9:51 AM
 */
@Service
public class HelloService {

    public static volatile boolean open = false;

    public void hello(String msg){

//        hello1(msg);
        hello2(msg);
    }



    //例1:
    // 先 http://localhost:8080/all?msg=777 等3秒
    // 再 http://localhost:8080/all?msg=open
    //a先响应
    //b等2秒后响应 ,因为得等a处理的完这个5秒,a处理3秒了还有2秒,b得等着。
    // start:XNIO-1 task-1  +++  Wed, 22 Jul 2020 02:06:34 GMT
    //start:XNIO-1 task-2  +++  Wed, 22 Jul 2020 02:06:37 GMT
    //service:XNIO-1 task-1  +++  Wed, 22 Jul 2020 02:06:44 GMT
    //end:XNIO-1 task-1  +++  Wed, 22 Jul 2020 02:06:44 GMT
    //service:XNIO-1 task-2  +++  Wed, 22 Jul 2020 02:06:49 GMT
    //end:XNIO-1 task-2  +++  Wed, 22 Jul 2020 02:06:49 GMT

    public synchronized void hello1(String msg){

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("service:"+Thread.currentThread().getName()+"  +++  "+DateUtils.toDateString(new Date()));
    }

    //例2:
    // 先 http://localhost:8080/all?msg=777 等3秒
    // 再 http://localhost:8080/all?msg=open
    //一起响应
    // start:XNIO-1 task-1  +++  Wed, 22 Jul 2020 02:31:23 GMT
    //不开锁:false++XNIO-1 task-1  +++  Wed, 22 Jul 2020 02:31:30 GMT
    //不开锁:false++XNIO-1 task-1  +++  Wed, 22 Jul 2020 02:31:32 GMT
    //不开锁:false++XNIO-1 task-1  +++  Wed, 22 Jul 2020 02:31:34 GMT
    //不开锁:false++XNIO-1 task-1  +++  Wed, 22 Jul 2020 02:31:36 GMT
    //start:XNIO-1 task-2  +++  Wed, 22 Jul 2020 02:31:37 GMT
    //不开锁:false++XNIO-1 task-1  +++  Wed, 22 Jul 2020 02:31:38 GMT
    //不开锁:false++XNIO-1 task-1  +++  Wed, 22 Jul 2020 02:31:40 GMT
    //不开锁:false++XNIO-1 task-1  +++  Wed, 22 Jul 2020 02:31:42 GMT
    //开锁:true++XNIO-1 task-2  +++  Wed, 22 Jul 2020 02:31:42 GMT
    //end:XNIO-1 task-2  +++  Wed, 22 Jul 2020 02:31:42 GMT
    //end:XNIO-1 task-1  +++  Wed, 22 Jul 2020 02:31:42 GMT
    public  void hello2(String msg){

        if(msg.equals("open")){
            open=true;
            System.out.println("开锁:"+open+"++"+Thread.currentThread().getName()+"  +++  "+DateUtils.toDateString(new Date()));
        }

        long start = System.currentTimeMillis();
        while (!open){
            long end = System.currentTimeMillis();
            if(end -start>2000){
                start = end;
                System.out.println("不开锁:"+open+"++"+Thread.currentThread().getName()+"  +++  "+DateUtils.toDateString(new Date()));
            }
        }
    }

}


主要模拟锁住数据,a和b是同步的。和使用volatile模拟数据处理完成a和b一起返回。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!