J a v a Java Java中线程的创建和使用
1.使用 R u n n e r a b l e Runnerable Runnerable的实现类。
package Exp4;
public class Demo01 {
public static void main(String[] args) {
Thread thread1 = Thread.currentThread(); //获取当前线程(main 线程)
//isAlive() 判断该线程是否存活
System.out.println("当前线程的名字:"+thread1.getName()+" "+(thread1.isAlive()?"存活态":"非存活态"));
HelloThread r = new HelloThread(); // 创建线程类实例
Thread t = new Thread(r); // 创建线程
t.start(); //启动线程一定会调用线程类实现的接口方法run()
//t.run(); //方法调用
}
}
class HelloThread implements Runnable { // 定义一个线程类
int i;
@Override
public void run() { //重写run()方法
Thread thread2 = Thread.currentThread(); //静态方法
//thread2.setName("my_thread");
System.out.println("当前线程的名字:"+thread2.getName()+" "+(thread2.isAlive()?"存活态":"非存活态"));
i = 0;
while (true) {
System.out.println("Hello " + i++);
if (i > 3)
break;
}
}
}
当前线程的名字:main 存活态
当前线程的名字:Thread-0 存活态
Hello 0
Hello 1
Hello 2
Hello 3
2.使用 T h r e a d Thread Thread的子类。
package Exp4;
public class Demo02 {
public static void main(String[] args) {
new HelloThread2().start();
}
}
class HelloThread2 extends Thread {
int i;
@Override
public void run() {
// super.run();
i = 0;
while (true) {
System.out.println("Hello " + i++);
if (i > 5)
break;
}
//System.out.println("此行代码不被执行");
}
}
Hello 0
Hello 1
Hello 2
Hello 3
Hello 4
Hello 5
3.使用 R u n n e r a b l e Runnerable Runnerable的匿名实现类来作为 T h r e a d Thread Thread的参数传入。
package Exp4;
public class Demo03 {
public static void main(String[] args) {
Thread thread1 = Thread.currentThread();
System.out.println("当前线程的名字:"+thread1.getName()+" "+(thread1.isAlive()?"存活态":"非存活态"));
new Thread(new Runnable() { //创建接口的匿名实现类及其实例;创建匿名子线程对象并运行
@Override
public void run() {
System.out.println("线程"+thread1.getName()+" "+(thread1.isAlive()?"存活态":"非存活态"));
Thread thread2 = Thread.currentThread();
//thread2.setName("my_thread");
System.out.println("当前线程的名字:"+thread2.getName()+" "+(thread2.isAlive()?"存活态":"非存活态"));
int i = 0;
while (true) {
System.out.println("Hello " + i++);
if (i > 3)
break;
}
}
}).start();
}
}
当前线程的名字:main 存活态
线程main 非存活态
当前线程的名字:Thread-0 存活态
Hello 0
Hello 1
Hello 2
Hello 3