您的位置:首页 > 编程语言 > Java开发

scala调用java api

2015-06-18 12:37 381 查看

1.看一个socket实例,直接调用java api即可

介绍java中的使用thread pool达到内部线程重用,在android也有msg的thread pool

Executors.newFixedThreadPool(poolSize)

* Creates a thread pool that reuses a fixed number of threads

* operating off a shared unbounded queue. At any point, at most

* <tt>nThreads</tt> threads will be active processing tasks.

* If additional tasks are submitted when all threads are active,

* they will wait in the queue until a thread is available.

* If any thread terminates due to a failure during execution

* prior to shutdown, a new one will take its place if needed to

* execute subsequent tasks. The threads in the pool will exist

* until it is explicitly
{@link ExecutorService#shutdown shutdown}

* Creates a thread pool that reuses a fixed number of threads

* operating off a shared unbounded queue. At any point, at most

* <tt>nThreads</tt> threads will be active processing tasks.

* If additional tasks are submitted when all threads are active,

* they will wait in the queue until a thread is available.

* If any thread terminates due to a failure during execution

* prior to shutdown, a new one will take its place if needed to

* execute subsequent tasks. The threads in the pool will exist

* until it is explicitly
{@link ExecutorService#shutdown shutdown}.

监听指定端口

class NetworkService(port: Int, poolSize: Int) extends Runnable {
val serverSocket = new ServerSocket(port)
val pool: ExecutorService = Executors.newFixedThreadPool(poolSize)

def run() {
try {
while (true) {
// This will block until a connection comes in.
val socket = serverSocket.accept()
pool.execute(new Handler(socket))
}
} finally {
pool.shutdown()
}
}
}


一旦端口绑定后就

class Handler(socket: Socket) extends Runnable {
def message = (Thread.currentThread.getName() + " Hello world\n").getBytes

def run() {
socket.getOutputStream.write(message)
socket.getOutputStream.close()
}
}
object Demo{
def main(args: Array[String]) {
(new NetworkService(2021, 2)).run
}
}




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: