public class ThreadDemo {
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
/*
* static Thread currentThread()
返回对当前正在执行的线程对象的引用。
*/
//System.out.println("main-->" + i);
Thread.currentThread().setName("主线程");
String name = Thread.currentThread().getName();
System.out.println(name+ "-->"+i);
if (i == 50) {
new MyThread("我创建的线程").start();
}
}
for (int i = 0; i < 200; i++) {
System.out.println("main = " + i);
if(i == 10){
new Thread(new MyThread2(), "AAA").start();
}
}
System.out.println("-------------------------");
new Thread(new Runnable() { //匿名内部类实现
@Override
public void run() {
for (int i = 0; i < 200; i++) {
System.out.println("匿名对象-->" + i);
}
}
}).start();
}
}
/*
* 创建线程的第一种方法:
* 1.定义一个类继承Thread类
* 2.复写run()方法
* 3.创建一个线程
* 4.启动线程
*/
class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 200; i++) {
System.out.println(super.getName() + i);
}
}
MyThread(String name) {
super(name);
// TODO Auto-generated constructor stub
}
}
/*
* 创建线程的第二种方法:
* 1.定义一个类MyThread实现Runnable接口
* 2.实现run()方法
* 3.线程对象的创建 new Thread(Runnable对象)
* 4.线程的启动
*/
class MyThread2 implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 100; i++) {
String name = Thread.currentThread().getName();
//System.out.println("MyThread2 = " + i);
System.out.println(name + "-->" + i);
}
}
} |
|