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

03_socket编程(补)_Java多线程1

2017-12-29 14:39 218 查看
下一节将要聊一下ServerSocket。并且会创建多线程的服务器,所以在这里先普及一下多线程的基础知识



1.定义任务:

编写多线程可以实现接口Runnable

package com.tcp.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class LiftOff implements Runnable {
protected int countDown = 5;
private static int taskCount = 0;
private final int id = taskCount++;
public LiftOff(){

}
public LiftOff(int countDown){
this.countDown = countDown;
}
public String status(){
return "#" + id + "(" + (countDown > 0 ? countDown : "liftOff") + ")";
}

@Override
public void run() {
while(countDown-- > 0){
System.out.println(status());
//			Thread.yield();
}
}

public static void main(String[] args) {
LiftOff lo = new LiftOff();
//		lo.run();
//		for(int i = 0 ; i < 50 ; i++){
//			System.out.println("main thread :"+i);
//		}

System.out.println("---------------------分割线------------------------");

//		Thread t = new Thread(lo);
//		t.start();
//		for(int i = 0 ; i < 50 ; i++){
//			System.out.println("main thread :"+i);
//		}

System.out.println("---------------------分割线------------------------");

//		ExecutorService exec = Executors.newCachedThreadPool();
//		exec.execute(lo);
//		for(int i = 0 ; i < 50 ; i++){
//			System.out.println("main thread :"+i);
//		}
//		exec.shutdown();

System.out.println("---------------------分割线------------------------");

//		ExecutorService exec = Executors.newFixedThreadPool(3);
//		for(int i = 0 ; i < 5 ; i++){
//			exec.execute(new LiftOff());
//		}
//		exec.shutdown();

System.out.println("---------------------分割线------------------------");

ExecutorService exec = Executors.newSingleThreadExecutor();
for(int i = 0 ; i < 5 ; i++){
exec.execute(new LiftOff());
}
for(int i = 0 ; i < 50 ; i++){
System.out.println("main thread :"+i);
}
exec.shutdown();

}

}

 代码描述:

创建了一个实现Runnable接口的类。在main中分别使用了不同的方法开启多线程。

第一种:没有开启多线程,只是调用了run方法

第二种:使用Thread.start()开启多线程

第三种:使用Executors.newCachedThreadPool()。然后调用execute开启多线程

第四种:Executors.newFixedThreadPool(3)。带有最大线程池,开启多线程

第五种:Executors.newSingleThreadExecutor();单个线程池,开启多线程。等价于Executors.newFixedThreadPool(1)

PS:最后记着调用exec.shutdown();这样才能将main线程结束掉

我们将main方法叫做主线程,Thread开启的叫做子线程。当调用start时。主线程和子线程开始并行



 
 





大小: 29.6 KB





大小: 18.2 KB

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