普通的程序中,方法的调用是执行到方法的时候,程序跳转到方法体中进行,是按照顺序进行的,而多线程则是多任务“同时”进行,即“边吃饭边看电视”,而不是“吃完饭再看电视”,多线程是并发执行的。(并发:短时刻内交替执行,宏观上是“同时”执行的)
可以这么理解:电脑上的QQ存储在硬盘中,是一个程序,当我们运行它的时候,它就成为了一个进程,得到了系统资源分配,而它的功能比如可以同时聊天同时打电话还可以逛空间和发邮件,这些诸多功能就是线程。
注意:很多多线程其实是模拟出来的,真正的多线程是指有多个CPU,即多核,如服务器。如果是模拟出来的多线程,即在一个CPU的情况下,在同一个时间点,CPU只能执行一个代码,但因为切换的很快,就有“同时”执行的错觉,这就是并发。
Java虚拟机允许应用程序同时执行多个执行线程,每个线程都有优先权
进程的创建有如下三种方式:
自定义线程类继承 Thread 类;
重写 run( ) 方法,编写程序执行体;
创建线程对象,调用 start( ) 方法启动线程;
通过打印输出来判断多线程的执行顺序:
//创建线程方式一:继承Thread类,重写run()方法,调用start()方法
public class TestThread01 extends Thread{@Overridepublic void run() {//run方法线程体for (int i = 0; i < 10; i++) {System.out.println("敲代码+"+i);}}public static void main(String[] args) {//main主线程//创建一个线程对象TestThread01 t1 = new TestThread01();//调用start()方法开启t1.start();for (int i = 0; i < 1000; i++) {System.out.println("学习Java+"+i);}}
}
运行可知,并没有按顺序执行,而是并发执行的(由CPU调度执行):
推荐使用 Runnable对象,因为Java单继承的局限性
//创建线程方式二:实现Runnable接口,重写run()方法,执行线程需要丢入Runnable接口实现类,调用start方法
public class TestThread02 implements Runnable{@Overridepublic void run() {//run方法线程体for (int i = 0; i < 10; i++) {System.out.println("敲代码+"+i);}}public static void main(String[] args) {//创建一个Runnable接口的实现类对象TestThread02 testThread02 = new TestThread02();/*创建线程对象,通过线程对象来开启线程Thread thread = new Thread(testThread02);thread.start();*/new Thread(testThread02).start();for (int i = 0; i < 1000; i++) {System.out.println("学习Java+"+i);}}}
对比 继承Thread类 和 实现Runnable接口 两种方法:
继承Thread类
- 子列继承Thread类具备多线程能力;
- 启动线程:子类对象.start( );
- 不建议使用:避免OOP单继承局限性;
实现Runnable接口
- 实现Runnable具有多线程能力;
- 启动线程:传入目标对象+Thread对象.start( );
- 推荐使用:避免单继承局限性,方便同一个对象被多个线程使用;
//进程创建方式三:实现Callable接口
public class TestCallable implements Callable {//重写call()方法@Overridepublic Boolean call() throws Exception {System.out.println("方法体");return true;}public static void main(String[] args) throws Exception {//创建对象TestCallable tc = new TestCallable();//创建执行服务ExecutorService ser = Executors.newFixedThreadPool(1);//提交执行Future result = ser.submit(tc);//通过服务提交线程//获取结果boolean b = result.get(); //call()方法返回类型//关闭服务ser.shutdown();}
}
Callable的好处:
- 可以定义返回值;
- 可以抛出异常;
Lambda表达式是一种特殊的表达语法,能够把一段代码像数据一样作为参数传递。> Lambda详解
能够避免内部类定义过多;
简化程序定义,只留下核心的逻辑,但会降低可读性;
语法:
(params) -> expression[表达式]
(params) -> statement[语句]
(params) -> {statements}
函数式接口的定义:任何接口,如果只包含唯一一个抽象方法,那么它就是一个函数式接口;
public interface Runnable{public abstract void run();
}对于函数式接口,可以通过Lambda表达式来创建该接口的对象
常规定义:
也可以使用 静态内部类(在类里面定义) :
还可以 局部内部类 (定义在方法里)和 匿名内部类(没有类名):
终极大招: Lambda简化
继续深入理解 Lambda 表达式:
简化:
前提是接口为函数式接口;
多个参数也可以去掉参数类型;
Lambda表达式只有在一行代码的情况下才能简化没有花括号;
相当于:
定义一个宠物类为真实对象,而主人类是代理对象,用主人类代理宠物类的方法:
public class StaticProxy {public static void main(String[] args) {Master master = new Master(new Pet());master.play();}
}interface Happy{//接口定义一个“玩”方法void play();
}//真实角色 宠物
class Pet implements Happy{@Overridepublic void play() {System.out.println("拼命拼命耍");}
}//代理角色 宠物的主人
class Master implements Happy{//代理谁(代理的真实角色)private Happy who;public Master(Happy who){this.who = who;//真实对象}private void before() {System.out.println("带狗出门");}private void after() {System.out.println("回家给狗洗澡");}@Overridepublic void play() {before();this.who.play();after();}
}
/*
输出:带狗出门拼命拼命耍回家给狗洗澡
/*
对于 多线程 的应用:
//创建一个Thread 静态代理Runnable接口
new Thread(new Runnable() {@Overridepublic void run() {System.out.println("今天去哪里玩了呀")}}).start();等同于如下:(使用lambda表达式)
//使用lambda表达式
new Thread(()-> System.out.println("今天去哪里玩了呀")).start();1.Thread是代理角色;
2.Runnable接口是真实角色;
3.Thread也实现Runnable接口;
3.所以Thread代理Runnable接口实现方法start();new Thread(()-> System.out.println("今天去哪里玩了呀")).start();相当于:new Master(new Pet()).play();Thread 和 Master 都是代理对象
Runnable 和 Pet 是真实对象
线程有五大状态:
public class TestStop implements Runnable{//1.设置一个标识位private boolean flag = true;@Overridepublic void run() {int i = 0;while(flag){System.out.println("run...Thread "+i++);}}//2.设置一个公开的方法停止线程,转换标志位public void stop(){ //自定义的停止方法this.flag = false;}public static void main(String[] args) {//创建Runnable实现类对象,通过线程对象开启线程TestStop testStop = new TestStop();new Thread(testStop).start();for (int i = 0; i < 1000; i++) {System.out.println("main线程 "+i);if (i==900){//调用stop方法切换标志位,让线程停止testStop.stop();System.out.println("线程停止");}}}
}
1 秒 = 1000 毫秒
倒计时 10、9、8 … 2、1 :
public class TestSleep implements Runnable {@Overridepublic void run() {for (int i = 10; i > 0; i--) {System.out.println(i);try {Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}}}public static void main(String[] args) {TestSleep testSleep = new TestSleep();new Thread(testSleep).start();}
}
//测试礼让线程
//礼让不一定成功,看CPU心情
public class TestYield {public static void main(String[] args) {MyYield myYield = new MyYield();new Thread(myYield,"a").start();new Thread(myYield,"b").start();}
}
class MyYield implements Runnable{@Overridepublic void run(){System.out.println(Thread.currentThread().getName()+"线程开始执行");Thread.yield();System.out.println(Thread.currentThread().getName()+"线程停止执行");}
}
运行结果如下(多种):
//测试join方法 相当于“插队”
public class TestJoin implements Runnable{@Overridepublic void run() {for (int i = 0; i < 1000; i++) {System.out.println("线程 BOSS 来啦"+i);}}public static void main(String[] args) throws InterruptedException {//启动线程TestJoin testJoin = new TestJoin();Thread thread = new Thread(testJoin);thread.start();//主线程for (int i = 0; i < 500; i++) {if(i==200){thread.join();//线程插队}System.out.println("main "+i);}}
} //如果子线程会穿插在主线程中,可以在run()中加个sleep()
/*main 0main 1...main 198main 199线程 BOSS 来啦0线程 BOSS 来啦1线程 BOSS 来啦2...线程 BOSS 来啦998线程 BOSS 来啦999main 200main 201...main 498main 499
*/
//观察线程状态
public class TestState {public static void main(String[] args) throws InterruptedException {Thread thread = new Thread(()->{ //Lambda表达式for (int i = 0; i < 5; i++) {try {Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}}System.out.println("-------------");});//观察状态Thread.State state = thread.getState();//观察启动后thread.start();state = thread.getState();System.out.println(state);//Run//只要线程不终止,就一直输出状态while(state!=Thread.State.TERMINATED){Thread.sleep(100);state = thread.getState();//更新线程状态System.out.println(state);//输出状态}thread.start();}
}
/* 输出:RUNNABLETIMED_WAITINGTIMED_WAITING......TIMED_WAITING-------------TERMINATED*/
//测试线程的优先级
public class TestPriority {public static void main(String[] args ){//主线程默认优先级System.out.println(Thread.currentThread().getName()+"--->Priority "+Thread.currentThread().getPriority());MyPriority myPriority = new MyPriority();Thread t1 = new Thread(myPriority);Thread t2 = new Thread(myPriority);Thread t3 = new Thread(myPriority);Thread t4 = new Thread(myPriority);//先设置优先级,再启动t1.start();t2.setPriority(1);t2.start();t3.setPriority(4);t3.start();t4.setPriority(Thread.MAX_PRIORITY);//MAX_PRIORITY=10t4.start();}
}
class MyPriority implements Runnable{@Overridepublic void run() {System.out.println(Thread.currentThread().getName()+"--->Priority "+Thread.currentThread().getPriority());}
}
/*
main--->Priority 5
Thread-0--->Priority 5
Thread-3--->Priority 10
Thread-2--->Priority 4
Thread-1--->Priority 1进程已结束,退出代码0*/
优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用,都是看CPU的调度
守护线程是程序运行的时候在后台提供一种通用服务的线程。
所有用户线程停止,进程才会停掉所有守护线程,退出程序。
//测试守护线程
//上帝守护你
public class TestDaemon {public static void main(String[] args) {God god = new God();You you = new You();Thread thread = new Thread(god);thread.setDaemon(true);//默认是false表示是用户线程,正常的线程都是用户线程thread.start();new Thread(you).start();//你 用户线程启动}
}
//上帝
class God implements Runnable{@Overridepublic void run(){while(true){System.out.println("上帝保佑你");}}
}
//你
class You implements Runnable{@Overridepublic void run(){for (int i = 0; i < 36500; i++) {System.out.println("开心快乐的活着");}System.out.println("--> goodbye world <--");}
} //可以自己运行一下,很有意思
现实生活中,会遇到“同一个资源,多个人都想使用”的问题,例如:食堂排队打饭,每个人都想吃饭,最简单的解决办法就是,排队,一个一个来。
处理多线程时,多个线程访问同一个对象,并且某些线程还想修改这个对象,这时候需要线程同步;线程同步其实就是一种 等待机制,多个需要同时访问此对象的线程进入到这个 对象的等待池 形成队列,等待前面线程使用完毕,下一个线程再使用。
这个时候需要两种东西: 队列 和 锁 ;
由于同一个进程的多个线程共享同一个存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入 锁机制 synchronized ,当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可,存在以下问题:
线程不同步,可能会出现拿到 -1张票的情况
//不安全的买票
//线程不安全,会出现负数
public class UnsafeBuyTicket {public static void main(String[] args){BuyTicket station = new BuyTicket();new Thread(station,"你").start();new Thread(station,"我").start();new Thread(station,"他").start();}
}
class BuyTicket implements Runnable{//票private int ticketNums = 10;boolean flag = true;//外部停止方式@Overridepublic void run(){while(flag){try {buy();} catch (InterruptedException e) {throw new RuntimeException(e);}}}private void buy() throws InterruptedException {//判断是否有票if(ticketNums <=0){flag = false;return;}//模拟延时Thread.sleep(100);//买票System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);}
}
多个线程同时对银行发起取钱,会导致出现取多了的情况
//不安全的取钱
//两个人去银行取钱,账户
public class UnsafeBank {public static void main(String[] args) {//账户Account account = new Account(100,"基金");Drawing you = new Drawing(account,50,"你");Drawing me = new Drawing(account,100,"我");you.start();me.start();}
}
//账户
class Account {int money;//余额String name;//卡名public Account(int money,String name){this.money = money;this.name = name;}
}
//银行:模拟取款
class Drawing extends Thread{Account account;//账户//取了多少钱int drawingMoney;//现在手里有多少钱int nowMoney;public Drawing(Account account,int drawingMoney,String name){super(name);this.account = account;this.drawingMoney = drawingMoney;}//取钱@Overridepublic void run(){//判断有没有钱if(account.money-drawingMoney<0){System.out.println(Thread.currentThread().getName()+"钱不够,取不了");return;}try {Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}//卡内余额 = 余额 - 取走的钱account.money = account.money - drawingMoney;//手里的钱nowMoney = nowMoney+ drawingMoney;System.out.println(account.name+"余额为"+account.money);//Thread.currentThread().getName() = this.getName;System.out.println(this.getName()+"手里的钱"+nowMoney);}
} /* 基金余额为-50你手里的钱50基金余额为-50我手里的钱100进程已结束,退出代码0
*/
//线程不安全的集合
public class UnsafeList {public static void main(String[] args) throws InterruptedException {List list = new ArrayList();for (int i = 0; i < 10000; i++) {new Thread(()->{list.add(Thread.currentThread().getName());}).start();}System.out.println(list.size());}
} /* 9997进程已结束,退出代码0
*/
由于可以通过 private 关键字可以保证数据对象只能被方法访问,所以只需针对方法提出一套机制,这套机制就是 synchronized 关键字,它包括两种用法:
同步方法:
public synchronized void method( int args){}
synchronized 方法控制对 “对象” 的访问,每个对象对应一把锁,每个 synchronized 方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行。
缺陷:若将一个大的方法声明为 synchronized 将会影响效率
弊端:方法里面需要修改的内容才需要锁,锁的太多,浪费资源,这个时候就需要 同步块 来解决
同步块:
解决之前不安全的买票:(同步方法)
//安全的买票
public class UnsafeBuyTicket {public static void main(String[] args){BuyTicket station = new BuyTicket();new Thread(station,"你").start();new Thread(station,"我").start();new Thread(station,"他").start();}
}class BuyTicket implements Runnable{//票private int ticketNums = 10;boolean flag = true;//外部停止方式@Overridepublic void run(){while(flag){try {buy();} catch (InterruptedException e) {throw new RuntimeException(e);}}}//synchronized 定义为同步方法,锁的是 thisprivate synchronized void buy() throws InterruptedException {//判断是否有票if(ticketNums <=0){flag = false;return;}//模拟延时Thread.sleep(100);//买票System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);}
}
解决不安全的银行:(同步块)
//安全的取钱
//两个人去银行取钱,账户
public class UnsafeBank {public static void main(String[] args) {//账户Account account = new Account(100,"基金");Drawing you = new Drawing(account,50,"你");Drawing me = new Drawing(account,100,"我");you.start();me.start();}}//账户
class Account {int money;//余额String name;//卡名public Account(int money,String name){this.money = money;this.name = name;}
}//银行:模拟取款
class Drawing extends Thread{Account account;//账户//取了多少钱int drawingMoney;//现在手里有多少钱int nowMoney;public Drawing(Account account,int drawingMoney,String name){super(name);this.account = account;this.drawingMoney = drawingMoney;}//取钱@Overridepublic void run(){//全部放到同步块中 监视accountsynchronized(account) {//判断有没有钱if(account.money-drawingMoney<0){System.out.println(Thread.currentThread().getName()+"钱不够,取不了");return;}try {Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}//卡内余额 = 余额 - 取走的钱account.money = account.money - drawingMoney;//手里的钱nowMoney = nowMoney+ drawingMoney;System.out.println(account.name+"余额为"+account.money);//Thread.currentThread().getName() = this.getName;System.out.println(this.getName()+"手里的钱"+nowMoney);}}
}/* 基金余额为50你手里的钱50我钱不够,取不了进程已结束,退出代码0
*/
解决不安全的集合:(同步块)
//线程安全的集合
public class UnsafeList {public static void main(String[] args) throws InterruptedException {List list = new ArrayList();for (int i = 0; i < 10000; i++) {new Thread(()->{synchronized (list){list.add(Thread.currentThread().getName());}}).start();}Thread.sleep(3000);System.out.println(list.size());}
} /* 10000进程已结束,退出代码0
*/
import java.util.concurrent.CopyOnWriteArrayList;
//测试JUC安全类型的集合 CopyOnWriteArrayList
public class UnsafeList {public static void main(String[] args) throws InterruptedException {CopyOnWriteArrayList list = new CopyOnWriteArrayList();for (int i = 0; i < 10000; i++) {new Thread(()->{list.add(Thread.currentThread().getName());}).start();}Thread.sleep(3000);System.out.println(list.size());}
} /* 10000进程已结束,退出代码0
*/
多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行,而导致两个或者多个线程都在等待对方释放资源,都停止执行的情形。某一个同步块同时拥有“ 两个以上对象的锁 ” 时,就可能会发生 " 死锁 " 问题。
简单来说就是,甲需要乙手中的东西,而乙又想要甲手中的东西,两者陷入死循环,这就是死锁。
例:有两个女生,一个是灰姑娘,一个是白雪公主,两人都想化妆,但一个有口红,一个有镜子,她们都互相想要对方手里的东西,陷入了僵持:这就是死锁
//死锁:多个线程互相抱着对方需要的资源,然后形成僵持
public class DeadLock {public static void main(String[] args) {Makeup girl1 = new Makeup(0,"灰姑娘");Makeup girl2 = new Makeup(1,"白雪公主");girl1.start();girl2.start();}
}//口红
class LipStick{}//镜子
class Mirror{}class Makeup extends Thread{//需要的资源只有一份,用static来保证只有一份(不然不同对象的都不同)static LipStick lipstick = new LipStick();static Mirror mirror = new Mirror();int choice;//选择String name;//使用化妆品的人Makeup(int choice,String name){this.choice = choice;this.name = name;}@Overridepublic void run() {//化妆try {makeup();} catch (InterruptedException e) {throw new RuntimeException(e);}}//化妆,互相持有对方的锁,就是需要拿到对方的资源private void makeup() throws InterruptedException {if(choice == 0){synchronized(lipstick) {System.out.println(this.name + "获得口红的锁");Thread.sleep(1000);//一秒钟后获得锁synchronized (mirror) {System.out.println(this.name+ "获得镜子的锁");Thread.sleep(1000);}}}else{synchronized(mirror){System.out.println(this.name+"获得镜子的锁");Thread.sleep(1000);//一秒钟后获得锁synchronized(lipstick){System.out.println(this.name+"获得口红的锁");Thread.sleep(1000);}}}}
}
产生死锁的四个必要条件:
只要破其中的任意一个或多个条件就可以避免死锁发生
class Test{private final ReentrantLock lock = new ReentrantLock();public void method(){lock.lock();try{//保证线程安全的代码}finally{lock.unlock();//如果同步代码有异常,要将unlock()写入finally语句块}}
}
synchronized 与 Lock 的对比:
- Lock是显示锁(手动开启和关闭锁,别忘记关锁)synchronized是隐式锁,出了作用域自动释放;
- Lock只有代码块锁,synchronized有代码块锁和方法锁;
- 使用 Lock锁,JVM将花费较少的时间来调度线程,性能更好,且具有更好的扩展性(提供更多的子类);
- 优先使用顺序:
- Lock > 同步代码块(已经进入方法体,分配了相应资源) > 同步方法(在方法体之外)
先看不加锁的,运行结果发现输出结果有误:
然后用 ReentrantLock 加锁解锁 解决:
//测试Lock锁
public class TestLock {public static void main(String[] args) {TestLock2 t= new TestLock2();new Thread(t).start();new Thread(t).start();new Thread(t).start();}
}
class TestLock2 implements Runnable{int ticketNums = 10;//定义Lock锁private final ReentrantLock lock = new ReentrantLock();@Overridepublic void run() {while(true){try{lock.lock();//加锁if(ticketNums>0){try {Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println(ticketNums--);}else{break;}}finally {//解锁lock.unlock();}}}
}
这是一个线程同步问题,生产者和消费者共享同一个资源,并且生产者和消费者之间相互依赖,互为条件:
Java提供了几个方法解决线程之间的通信问题:
并发协作模型:生产者消费者模式-----> 管程法(增加缓冲区)
生产者将生产好的数据放入缓冲区,消费者从缓冲区拿出数据
//测试:生产者消费者模型--->利用缓冲区解决:管程法
//生产者,消费者,产品,缓冲区
public class TestPC {public static void main(String[] args) {//创建一个容器SynContainer container = new SynContainer();new Producer(container).start();new Consumer(container).start();}
}//生产者
class Producer extends Thread{SynContainer container;public Producer(SynContainer container){this.container = container;}//生产@Overridepublic void run() {for (int i = 0; i < 100; i++) {try {container.push(new Food(i));} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println("生产了"+i+"个好吃的");}}
}//消费者
class Consumer extends Thread{SynContainer container;public Consumer(SynContainer container){this.container = container;}//消费@Overridepublic void run(){for (int i = 0; i < 100; i++) {try {System.out.println("消费了--->"+container.buy().id+"个好吃的");} catch (InterruptedException e) {throw new RuntimeException(e);}}}
}//产品
class Food{int id;//产品编号public Food(int id) {this.id = id;}
}//缓冲区
class SynContainer{//需要一个容器大小Food[] foods = new Food[10];//容器计数器int count = 0 ;//生产者放入产品public synchronized void push(Food food) throws InterruptedException {//如果容器满了,就需要等待消费者消费if(count==foods.length){//通知消费者消费,生产者等待this.wait();}//如果没有满,就需要丢入产品foods[count]=food;count++;//可以通知消费者消费了this.notifyAll();}public synchronized Food buy() throws InterruptedException {//判断能否消费if(count==0){//等待生产者生产,消费者等待this.wait();}//如果可以消费count--;Food food = foods[count];//吃完了,通知生产者生产this.notifyAll();return food;}
}
并发协作模型:生产者消费者模式-----> 信号灯法(设标志位)
//测试生产者消费者问题2:信号灯法-->标志位解决
public class TestPC2 {public static void main(String[] args) {TV tv = new TV();new Player(tv).start();new Watcher(tv).start();}
}//生产者--->演员
class Player extends Thread{TV tv;public Player(TV tv){this.tv = tv;}@Overridepublic void run(){for (int i = 0; i < 20; i++) {if(i%2==0){try {this.tv.play("快乐大本营播放中");} catch (InterruptedException e) {throw new RuntimeException(e);}}else{System.out.println("广告时间。。。。");}}}
}//消费者--->观众
class Watcher extends Thread{TV tv;public Watcher(TV tv){this.tv = tv;}@Overridepublic void run(){for (int i = 0; i < 20; i++) {try {tv.watch();} catch (InterruptedException e) {throw new RuntimeException(e);}}}
}//产品--->节目
class TV{//演员表演,观众等待 T//观众观看,演员等待 FString program ;//表演节目boolean flag = true;//表演public synchronized void play(String program) throws InterruptedException {if(!flag){this.wait();}System.out.println("演员表演--> "+program);//通知观众观看this.notifyAll();//通知唤醒this.program = program;this.flag = !this.flag;}//观看public synchronized void watch() throws InterruptedException {if(flag){this.wait();}System.out.println("观看了"+program);//通知演员表演this.notifyAll();this.flag = !this.flag;}
}
背景:经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大;
思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中;
好处:
使用线程池:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;//测试线程池
public class TestPool {public static void main(String[] args) {//1.创建服务,创建线程池//newFixedThreadPool 参数为线程池大小ExecutorService service = Executors.newFixedThreadPool(10);service.execute(new MyThread());service.execute(new MyThread());service.execute(new MyThread());service.execute(new MyThread());service.execute(new MyThread());//2.关闭链接service.shutdown();}
}
//线程类实现Runnable接口
class MyThread implements Runnable{@Overridepublic void run(){System.out.println(Thread.currentThread().getName());}
}