javascript多線程實例詳解

一、什麼是多線程

這裡寫圖片描述

這裡寫圖片描述

二、Concurrent.Thread.js

<meta charset="utf-8" />
<script src="Concurrent.Thread.js"></script>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>

<style>
    p{
        width:100px;
        height: 100px;
        cursor: pointer;
        background: orange;
    }
</style>

<p id="test">
    測試點擊
</p>


<script>
    Concurrent.Thread.create(function(){
        $('#test').click(function(){
            alert(1);
        });

        // 下面有一段特別復雜的函數
        for(var i = 0;i < 1000000;i++){
            console.log(i);
        }
    });

</script>

<!--
    /**
     * 異步事件隊列,負責執行alert(1)
    */-->

這裡寫圖片描述

三、WebWork

index.html

<meta charset="utf-8" />
<!--<script src="Concurrent.Thread.js"></script>-->
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>

<style>
    p{
        width:100px;
        height: 100px;
        cursor: pointer;
        background: orange;
    }
</style>

<p id="test">
    測試點擊
</p>


<script>
  $('#test').click(function(){
      alert(1);
  });
  var worker = new Worker('task.js');
  worker.onmessage = function(event){
      alert(event.data);
  }
  worker.postMessage(100000);

</script>

task.js

onmessage = function(event){
    var num = event.data;
    var result = 0;
    for(var i = 0;i< num;i++){
        result +=i;
    }
    // 向線程創建源送回消息
    postMessage(result);
}

這裡寫圖片描述

ShareWebWorker

共享型web worker主要適用於多連接並發的問題

index.html

<meta charset="utf-8" />
<!--<script src="Concurrent.Thread.js"></script>-->
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>

<style>
    p{
        width:100px;
        height: 100px;
        cursor: pointer;
        background: orange;
    }
</style>

<p id="test">
    測試點擊
</p>


<script>
  $('#test').click(function(){
      alert(1);
  });

var worker = new SharedWorker('task.js');
worker.port.addEventListener('message',function(e){
    console.log(e.data);
},false)

// 發送信息
worker.port.start();
worker.port.postMessage(100);

</script>

task.js

var result = 0;
onconnect = function(e){
    var port = e.ports[0];
    port.postMessage('connection success!');
    port.onmessage = function(e){
        if(e.data !== 'get'){
            for(var i = 0;i < e.data;i++){
                result += i;
            }
        }
        port.postMessage(result);
    }
}

test.html

<meta charset="utf-8" />
<!--<script src="Concurrent.Thread.js"></script>-->
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>

<style>
    p{
        width:100px;
        height: 100px;
        cursor: pointer;
        background: orange;
    }
</style>

<p id="test">
    測試點擊
</p>


<script>
  $('#test').click(function(){
      alert(1);
  });

var worker = new SharedWorker('task.js');
worker.port.addEventListener('message',function(e){
    alert(e.data);
},false)

// 發送信息
worker.port.start();
worker.port.postMessage('get');

</script>

這裡寫圖片描述

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *