一、多线程的两种创建方式
1、继承Thread类,重写Thread类的run方法。
package com.thread.student;
/**
* 线程的创建方式:
* 1,继承Thread,重写Thread的run()方法(线程体)
* @author dgw
*
*/
public class CreateThread extends Thread{
@Override
public void run() {
for(int i=0;i<10000;i++){
System.out.println("张无忌出招:"+i);
}
}
}
class CreateThread01 extends Thread{
@Override
public void run() {
for(int i=0;i<10000;i++){
System.out.println("周芷若出招:"+i);
}
}
}
package com.thread.student;
public class CreateThreadTest {
public static void main(String[] args) {
//张无忌线程
CreateThread createThread = new CreateThread();
//周芷若线程
CreateThread01 createThread01 = new CreateThread01();
createThread.start();
createThread01.start();
// 张无忌出招:9919
// 周芷若出招:6365
// 周芷若出招:6366
// 周芷若出招:6367
// 周芷若出招:6368
// 周芷若出招:6369
// 周芷若出招:6370
// 周芷若出招:6371
}
}
2、静态代理创建线程类,实现Runnable接口。
静态代理需要满足,目标类和代理类实现共同的接口。由于Thread类已经实现了Runable接口,我们只需要实现Runable类,用Thread类来作为我们的代理类。创建多个线程即可。由于java是单继承的,所以如果目标线程类继承了Thread类,可能会导致无法继承其他类。
package com.thread.student;
public class TargetThread implements Runnable{
int i=0;
@Override
public void run() {
i++;
System.out.println("线程"+i+"开始了");
}
public static void main(String[] args) {
TargetThread targetThread = new TargetThread();
Thread thread1 = new Thread(targetThread);
Thread thread2 = new Thread(targetThread);
Thread thread3 = new Thread(targetThread);
thread1.start();
thread3.start();
thread2.start();
// 线程1开始了
// 线程2开始了
// 线程3开始了
}
}