最新消息: USBMI致力于为网友们分享Windows、安卓、IOS等主流手机系统相关的资讯以及评测、同时提供相关教程、应用、软件下载等服务。

java多线程join方法

互联网 admin 1浏览 0评论

java多线程join方法

                                        java多线程join方法

java中多线程是异步执行的,我们想要多线程按照一定的顺序执行,需要加锁,或者在其他线程start之前加join。

来看看实例:

package Test;public class ThreadNum extends Thread{private int first;public ThreadNum(String name,int first) {super(name);this.first=first;}public void run() {System.out.print("当前执行线程是:"+this.getName()+"  ");for(int i=first;i<20;i+=2) {System.out.print(i+"\t");}System.out.println(this.getName()+"结束");}public static void main(String[] args) {System.out.println("当前的线程是"+Thread.currentThread().getName());ThreadNum odd=new ThreadNum("奇数线程", 1);ThreadNum even=new ThreadNum("偶数线程", 2);odd.setPriority(1);odd.start();try {odd.join();} catch (InterruptedException e2) {// TODO Auto-generated catch blocke2.printStackTrace();}even.start();try {odd.join();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}try {even.join();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("当前活动的线程是"+Thread.activeCount());}}

如果不在奇数线程start后面偶数线程start之前加join,奇偶线程就会交替执行。

join是在一个线程start之后,在其他线程start之前用。这样就达到了同步执行线程的目的。

线程在调用join之后,会让其他线程包括主函数的线程也会停止运行。

如果其他join写在了其他线程之后,不会影响其他线程的异步执行。

java多线程join方法

                                        java多线程join方法

java中多线程是异步执行的,我们想要多线程按照一定的顺序执行,需要加锁,或者在其他线程start之前加join。

来看看实例:

package Test;public class ThreadNum extends Thread{private int first;public ThreadNum(String name,int first) {super(name);this.first=first;}public void run() {System.out.print("当前执行线程是:"+this.getName()+"  ");for(int i=first;i<20;i+=2) {System.out.print(i+"\t");}System.out.println(this.getName()+"结束");}public static void main(String[] args) {System.out.println("当前的线程是"+Thread.currentThread().getName());ThreadNum odd=new ThreadNum("奇数线程", 1);ThreadNum even=new ThreadNum("偶数线程", 2);odd.setPriority(1);odd.start();try {odd.join();} catch (InterruptedException e2) {// TODO Auto-generated catch blocke2.printStackTrace();}even.start();try {odd.join();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}try {even.join();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("当前活动的线程是"+Thread.activeCount());}}

如果不在奇数线程start后面偶数线程start之前加join,奇偶线程就会交替执行。

join是在一个线程start之后,在其他线程start之前用。这样就达到了同步执行线程的目的。

线程在调用join之后,会让其他线程包括主函数的线程也会停止运行。

如果其他join写在了其他线程之后,不会影响其他线程的异步执行。

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论