您的位置:首页 > 其它

一些基础的线程例子

2010-10-11 11:28 246 查看
1.建立线程的方式:继承Thread类和实现Runnable接口。下面这个例子是通过继承类的方式创建线程的。

package mythread;

public class Thread1 extends Thread

{

public void run()

{

System.out.println(this.getName());

}

public static void main(String[] args)

{

System.out.println(Thread.currentThread().getName());

Thread1 thread1 = new Thread1();

Thread1 thread2 = new Thread1 ();

thread1.start();

thread2.start();

}

}

上面的代码建立了两个线程:thread1和thread2。上述代码中的005至008行是Thread1类的run方法。当在014和015行调用start方法时,系统会自动调用run方法。在007行使用this.getName()输出了当前线程的名字,由于在建立线程时并未指定线程名,因此,所输出的线程名是系统的默认值,也就是Thread-n的形式。在011行输出了主线程的线程名。

下面这个例子是通过实现Runnbale借口建立线程的

public class MyRunnable implements Runnable

{

public void run()

{

System.out.println(Thread.currentThread().getName());

}

public static void main(String[] args)

{

MyRunnable t1 = new MyRunnable();

MyRunnable t2 = new MyRunnable();

Thread thread1 = new Thread(t1, "MyThread1");

Thread thread2 = new Thread(t2);

thread2.setName("MyThread2");

thread1.start();

thread2.start();

}

}

2.为每个线程取名字的方式:Thread类有一个重载构造方法可以设置线程名 和 使用Thread类的setName方法修改线程名。

package mythread;

public class Thread2 extends Thread

{

private String who;

public void run()

{

System.out.println(who + ":" + this.getName());

}

public Thread2(String who)

{

super();

this.who = who;

}

public Thread2(String who, String name)

{

super(name);

this.who = who;

}

public static void main(String[] args)

{

Thread2 thread1 = new Thread2 ("thread1", "MyThread1");

Thread2 thread2 = new Thread2 ("thread2");

Thread2 thread3 = new Thread2 ("thread3");

thread2.setName("MyThread2");

thread1.start();

thread2.start();

thread3.start();

}

在main方法中建立了三个线程:thread1、thread2和thread3。其中thread1通过构造方法来设置线程名,thread2通过setName方法来修改线程名,thread3未设置线程名。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: