2016-07-01
1 继承Thread类创建线程
class 类名 extends Thread{
public void runa(){
//相关代码
}
}
package com.java1995; /** * 继承Thread类创建线程 * @author Administrator * */ public class MyThread extends Thread{ //构造器:给线程命名 public MyThread(String name){ super(name); } //重写run()方法 public void run(){ for(int i=0;i<10;i++){ try{ Thread.sleep(1000); }catch(InterruptedException e){ e.printStackTrace(); }//1000毫秒 System.out.println("MyThread"+i); } } }
package com.java1995; public class ThreadDemo { public static void main(String[] args) { MyThread mt=new MyThread("线程1"); MyThread mt2=new MyThread("线程2"); mt.start();//多线程 mt2.start(); //mt.run();//单线程 for(int i=0;i<10;i++){ try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("主线程"+i); } System.out.println("程序执行完毕"); } }
【参考资料】
时间: 2024-12-21 12:05:02