标签:over set com join() stack imp 指定 自己 其它
创建一个有名称的线程对象
package com.thread.mothed; public class ThreadMethod { public static void main(String[] args) { SubThread subThread = new SubThread(); Thread thread = new Thread(subThread, "线程一"); thread.start(); } } class SubThread implements Runnable { @Override public void run() { for (int j = 1; j <= 20; j++) { System.out.println(Thread.currentThread().getName() + ": " + j); } } }
package com.thread.mothed; public class ThreadMethod { public static void main(String[] args) { SubThread subThread = new SubThread(); Thread thread = new Thread(subThread); thread.setName("线程二"); thread.start(); } } class SubThread implements Runnable { @Override public void run() { for (int j = 1; j <= 20; j++) { System.out.println(Thread.currentThread().getName() + ": " + j); } } }
把指定的线程加入到当前线程,直到指定线程执行完毕,当前线程才会继续执行
package com.thread.mothed; public class ThreadMethod { public static void main(String[] args) { Thread thread=new Thread(new SubThread()); thread.start(); for(int i=1;i<=20;i++) { System.out.println(Thread.currentThread().getName()+": "+i); if(i==10) { try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } class SubThread implements Runnable{ @Override public void run() { for(int j=1;j<=20;j++) { System.out.println(Thread.currentThread().getName()+": "+j); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
使当前正在执行的线程以指定的毫秒数暂停
package com.thread.mothed; public class ThreadMethod { public static void main(String[] args) { for (int i = 1; i <= 20; i++) { System.out.println(Thread.currentThread().getName() + ": " + i); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
暂停当前正在执行的线程对象,让自己或者其它的线程运行
package com.thread.mothed; public class ThreadMethod { public static void main(String[] args) { Thread thread=new Thread(new SubThread()); thread.start(); for(int i=1;i<=50;i++) { System.out.println(Thread.currentThread().getName()+": "+i); if(i==25) { thread.yield(); System.out.println("-----------------"); } } } } class SubThread implements Runnable{ @Override public void run() { for(int j=1;j<=50;j++) { System.out.println(Thread.currentThread().getName()+": "+j); } } }
标签:over set com join() stack imp 指定 自己 其它
原文地址:https://www.cnblogs.com/fengfuwanliu/p/10166905.html