流行编程语言的详细对比(9)--线程建立

来源:互联网 发布:双倍定金怎么算法 编辑:程序博客网 时间:2024/06/16 22:55

Java
继承Thread
1)定义Thread的子类,实现run()方法
2)创建Thread子类的对象  
[创建之后,线程处于新建状态]
3)调用线程对象的start方法  
[线程处于就绪状态]

实现runnable或者callable
1)定义类,实现runnable接口,重写run方法
2)创建上述类类的对象  
[创建之后,线程处于新建状态]
3)不直接调用上述对象的start方法,而是将其作为target。new Thread(对象).start() 
[线程处于就绪状态]

Js
前端:
javascript是JS运行在浏览器中,是单线程的,
每个window一个JS线程,
JavaScript:
(1)setTimeout()使用 setTimeout() 分隔任务,间隔执行,改善响应
(2)使用 Web Worker建立工作线程

后端node.js:
(1)tagg2模块建立子线程
(2)cluster模块启动

Python
Python中使用线程有两种方式:
函数或者用类来包装线程对象。
(1)函数式:调用thread模块中的start_new_thread()函数来产生新线程。语法如下:
thread.start_new_thread ( function, args[, kwargs] )
(2)使用Threading模块创建线程
使用Threading模块创建线程,直接从threading.Thread继承,然后重写init方法和run方法:
thread1.start()

Go
一个goroutine并不相当于一个线程,
goroutine的出现正是为了替代原来的线程概念成为最小的调度单位。一旦运行goroutine时,先去当前线程查找,如果线程阻塞了,则被分配到空闲的线程,
如果没有空闲的线程,那么就会新建一个线程。
注意的是,当goroutine执行完毕后,
线程不会回收推出,而是成为了空闲的线程。

Scala
Runnable/Callable
区别:Runnable无返回值,Callable线程执行完有返回值

Runnable示例

import java.util.concurrent.{Executors, ExecutorService}object Test {  def main(args: Array[String]) {    //创建线程池    val threadPool:ExecutorService=Executors.newFixedThreadPool(5)    try {      //提交5个线程      for(i <- 1 to 5){        //threadPool.submit(new ThreadDemo("thread"+i))        threadPool.execute(new ThreadDemo("thread"+i))      }    }finally {      threadPool.shutdown()    }  }  //定义线程类,每打印一次睡眠100毫秒  class ThreadDemo(threadName:String) extends Runnable{    override def run(){      for(i <- 1 to 10){        println(threadName+"|"+i)        Thread.sleep(100)      }    }  }}

Callable示例

import java.util.concurrent.{Callable, FutureTask, Executors, ExecutorService}object Test {  def main(args: Array[String]) {    val threadPool:ExecutorService=Executors.newFixedThreadPool(3)    try {      val future=new FutureTask[String](new Callable[String] {        override def call(): String = {          Thread.sleep(100)          return "im result"        }      })      threadPool.execute(future)      println(future.get())    }finally {      threadPool.shutdown()    }  }}

PHP
1.Thread

<?phpclass HelloWorld extends Thread {    public function __construct($world) {       $this->world = $world;    }    public function run() {        print_r(sprintf("Hello %s\n", $this->world));    }}$thread = new HelloWorld("World");if ($thread->start()) {    printf("Thread #%lu says: %s\n", $thread->getThreadId(), $thread->join());}?>

2.Worker, Stackable

<?phpclass SQLQuery extends Stackable {        public function __construct($sql) {                $this->sql = $sql;        }        public function run() {                $dbh  = $this->worker->getConnection();                $row = $dbh->query($this->sql);                while($member = $row->fetch(PDO::FETCH_ASSOC)){                        print_r($member);                }        }}class ExampleWorker extends Worker {        public static $dbh;        public function __construct($name) {        }        /*        * The run method should just prepare the environment for the work that is coming ...        */        public function run(){                self::$dbh = new PDO('mysql:host=192.168.2.1;dbname=example','www','123456');        }        public function getConnection(){                return self::$dbh;        }}$worker = new ExampleWorker("My Worker Thread");$work=new SQLQuery('select * from members order by id desc limit 5');$worker->stack($work);$table1 = new SQLQuery('select * from demousers limit 2');$worker->stack($table1);$worker->start();$worker->shutdown();?>
原创粉丝点击