java之多线程
public class Test1 extends Thread{ private String name; public Test1(String name) { this.name=name; } public void run() { for(int i=0;i<10;i++) { System.out.println(name+"运行 i+"+i); } } }
public class TestDemo { public static void main(String[] args) { Test1 t1=new Test1("A"); Test1 t2=new Test1("B"); t1.start(); t2.start(); } }
run方式是写的方法,而start方法则是定在在jdk中
接口Runnable
public class Test2 implements Runnable{ private String name; public Test2(String name) { this.name=name; } public void run() { for(int i=0;i<10;i++) { System.out.println(name+"运行 i+"+i); } } }
public class Test2Demo { public static void main(String[] args){ Test2 t1=new Test2("A"); Test2 t2=new Test2("B"); Thread d1=new Thread(t1); Thread d2=new Thread(t2); try { d1.start(); d2.start(); }catch(IllegalThreadStateException e) { e.printStackTrace(); } } }
这里要抛出一个异常,
浙公网安备 33010602011771号