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 } }
相关文章推荐
- java——hello word
- 跟我学Java安全编程系列
- JAVA语言的特点
- 线程中start方法与run方法的区别-java教程
- 快速排序
- java读取excel并操作数据
- Java中使用DecimalFormat来设置输出小数的位数
- java.net.BindException: Address already in use <null>:8081
- 我的Java开发学习之旅------>Java经典排序算法之选择排序
- Eclipse jar打包详解
- 解决Java Web项目中文乱码的方法
- spring 注解事务
- java接口的基本使用
- Java-马士兵设计模式学习笔记-策略模式-模拟Comparable接口
- ZH奶酪:Java调用NLPIR汉语分词系统
- MyEclipse移动Web模拟器指南(二)
- java NIO
- LeetCode_40---Combination Sum II
- Java使用itext生成PDF报表
- 史上最详细版!java文件打包成exe,在未配置安装JDK和未配置的电脑上运行--转载