概述
- 作用
- 编程要点
作用
- 实现程序并行执行,提高效率
编程要点
- run()方法编写多线程,它是线程的主体,当启动线程时,会执行线程的run()方法
- start()方法启动多线程
- sleep()方法用于休眠当前线程指定的毫秒数
示例
- 示例1:
class testThread extends Thread{ public testThread(String str){ super(str); } public void run(){ for (int i = 0; i < 3; i++) { System.out.println(getName()+" Now running"); try { sleep(1000); } catch (InterruptedException e) { } System.out.println(getName()+" End"); } } } public class Hmain { public static void main(String[] args) { testThread thread1 = new testThread("Thread1"); testThread thread2 = new testThread("Thread2"); System.out.println(white.getId()); System.out.println(black.getId()); System.out.println(white.getName()); System.out.println(black.getName()); thread1.start(); thread2.start(); } }
- 示例2:
public class ThreadDemo extends Thread{ private String name=null; public ThreadDemo(String name){ this.name=name; } public void run() { while(true){ System.out.println(name+": Now running"); try { Thread.sleep((int)(Math.random()*10000)); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { Thread white=new ThreadDemo("white"); Thread black=new ThreadDemo("\tblack"); white.start(); black.start(); } }