j2se线程使用的两种方法

来源:互联网 发布:阿里云视频点播服务 编辑:程序博客网 时间:2024/06/05 14:20
public class my_thread {public static void main(String[] args) {cat c = new cat();//启动线程,会导致run方法运行。这是继承tread的方法c.start();//第二种方法runnable的启动,这是实现接口的方法。dog d = new dog();//先创建线程Thread t = new Thread(d);t.start();}}//通过继承父类Thread,实现线程操作,但是由于java不支持多重继承,所以最好用实现接口的办法class cat extends Thread{int times = 0;//重写run函数public void run(){while(true){//休眠时间,sleep会使线程进入阻塞。try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}times++;System.out.println("hello world");if(times == 10){break;}}}}//使用继承Runnable接口的办法,避免java中无法多重继承的问题。class dog implements Runnable{int times = 0;@Overridepublic void run() {while(true){try {Thread.sleep(2000);times++;System.out.println("runnable");if(times == 10){break;}} catch (Exception e) {// TODO: handle exception}}}}

0 0
原创粉丝点击