您的位置:首页 > 其它

线程的继承和实现

2012-11-09 17:34 99 查看
package Thread;

import java.text.DecimalFormat;

public class xiancheng {

/**

* @param Thread , Runnable

* >> 实现功能都一样,但Runnable是面向接口,扩展性比extends Thread 好;

* >> java是单继承,而接口可以实现多个;

*/

public static class xc{

public static long a=0;
public static Object obj=new Object();
public static void fun(){

synchronized (obj) {

DecimalFormat df=new DecimalFormat("000");

System.out.println(Thread.currentThread().getName()+":"+df.format(a));

a++;

if(a>999){

System.exit(0);

}

}

}

}

public static class xc1 extends Thread{

public void run() {

while(true){

try {

Thread.sleep(10);

} catch (Exception e) {

e.printStackTrace();

}

xc.fun();

}

}

}

public static class xc2 implements Runnable{

public void run() {

while(true){

try {

Thread.sleep(10);

} catch (Exception e) {

e.printStackTrace();

}

xc.fun();

}

}

}

public static void main(String[] args) {

xc1 x1 = new xc1();
xc2 x2 = new xc2();
Thread t1=new Thread(x1);
t1.setName("t1");
Thread t2=new Thread(x2);
t2.setName("t2");
Thread t3=new Thread(x1);
t3.setName("t3");
Thread t4=new Thread(x2);
t4.setName("t4");
t1.start();
t2.start();
t3.start();
t4.start();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: