1.效果图:
2.代码:
//可以继承Thread重写run函数public class MultipleThreadStudy extends Thread { /* MultipleThreadStudy(){} MultipleThreadStudy(String name){ super(name); }*/ //重写Thread的run函数 public void run(){ for(int i=0;i<10;i++) { System.out.PRint("MultipleThreadStudy:i="+i); try { Thread.sleep((int)Math.random()*1000); } catch(Exception e) { e.printStackTrace(); } System.out.println(""); } } //******************************************多线程********************************************************* //不论是用继承的Thread方法还是用Runnable接口实现的方法,java里面的多个线程同时运行时,不是顺序执行,而是并行执行 //如果需要顺序执行,则需加判断前一个线程是否执行完毕 //如果要顺序执行,方法一:判断线程isAlive是否在运行中,不停循环直至结束 //方法二:调用join方法 //快捷键注释代码:Ctrl+Shift+/ (/* */ 形式的) 或 Ctrl+/ (// 形式的) //快捷键取消注释:Ctrl+Shift+/ (/* */ 形式的) 或 Ctrl+/ (// 形式的) public static void main(String[] args) { //************继承Thread重写run函数的线程*************** MultipleThreadStudy thread1=new MultipleThreadStudy(); MultipleThreadStudy thread2=new MultipleThreadStudy(); MultipleThreadStudy thread3=new MultipleThreadStudy(); //thread1.setPriority(1); //设置优先级 //thread2.setPriority(2); //thread3.setPriority(3); System.out.println("............thread1 run..............."); thread1.start(); //方法一:判断线程isAlive是否在运行中,不停循环直至结束 while(thread1.isAlive()) { try { Thread.sleep(100); } catch(Exception e) { e.printStackTrace(); } } System.out.println("............thread2 run..............."); thread2.start(); while(thread2.isAlive()) { try { Thread.sleep(100); } catch(Exception e) { e.printStackTrace(); } } System.out.println("............thread3 run..............."); thread3.start(); while(thread3.isAlive()) { try { Thread.sleep(100); } catch(Exception e) { e.printStackTrace(); } } //************实现Runnable的接口方法run函数************* Runnable rb1=new RunnableThread(); Runnable rb2=new RunnableThread(); Runnable rb3=new RunnableThread(); Thread runnableThread1=new Thread(rb1);//鼠标移到Thread,按alt+/的方式看需传的参数 Thread runnableThread2=new Thread(rb2); Thread runnableThread3=new Thread(rb3); System.out.println("...runnableThread1 run..."); runnableThread1.start(); //方法二:调用join方法 try { runnableThread1.join(); } catch(Exception e) { e.printStackTrace(); } System.out.println("...runnableThread2 run..."); runnableThread2.start(); try { runnableThread2.join(); } catch(Exception e) { e.printStackTrace(); } System.out.println("...runnableThread3 run..."); runnableThread3.start(); }}//可以实现Runnable的接口方法run函数class RunnableThread implements Runnable{ public void run(){ for(int i=0;i<10;i++) { System.out.print("RunnableThread:i="+i); try { Thread.sleep((int)Math.random()*1000); } catch(Exception e) { e.printStackTrace(); } System.out.println(""); } }}
新闻热点
疑难解答