java多线程
java实现多线程有两种方式:一种是继承Thread类,另外一种是实现Runnable接口
用个程序举例:
/**
* 继承Thread类,直接调用run方法
* */
class Hello extends Thread {
public Hello () {
}
public Hello (String name) {
this.name = name;
}
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(name + "运行 " + i);
}
}
public static void main(String[] args) {
Hello h=new Hello ("A");
h.start();
}
private String name;
}
另外一种是实现Runnable接口
View Code
/** * 实现Runnable接口 * */ class Hello implements Runnable { public Hello () { } public Hello (String name) { this.name = name; } public void run() { for (int i = 0; i < 5; i++) { System.out.println(name + "运行 " + i); } } public static void main(String[] args) { Hello h1=new Hello ("线程"); Thread th= new Thread(h1); th.start(); } private String name; }
注意main方法中,是将实例化的对象作为Thread的参数: Hello h=new Hello ("线程");
Thread demo1=new Thread(h);关于选择继承Thread还是实现Runnable接口?
其实Thread也是实现Runnable接口的:
class Thread implements Runnable { public void run() { if (target != null) { target.run(); } } }
posted on 2012-08-21 22:59 Alan's Blog 阅读(397) 评论(0) 收藏 举报

浙公网安备 33010602011771号