子进程创建的三种方法
实现Runnable接口
package com.it_51;
public class Runner implements Runnable {
//编写执行代码
@Override
public void run(){
for(int i=0;i<10;i++){
//打印次数和线程名称
System.out.printf("%d,%s\n",i,Thread.currentThread().getName());
try{
//随机生成休眠时间
long sleepTime=(long) (1000*Math.random());
//线程休眠
Thread.sleep(sleepTime);
}catch (InterruptedException e){
System.out.println(e);
}
}
//线程执行结束
System.out.println("执行完毕!"+Thread.currentThread().getName());
}
}
继承Thrad类
package com.it_51;
public class ExtendThread extends Thread {
public ExtendThread(){
super();
}
public ExtendThread(String name){
super(name);
}
//编写执行代码
@Override
public void run(){
for(int i=0;i<10;i++){
try{
//打印次数和线程名称
System.out.printf("%d,%s\n",i,Thread.currentThread().getName());
//随机生成休眠时间
long sleepTime=(long) (1000*Math.random());
//线程休眠
Thread.sleep(sleepTime);
}catch (InterruptedException e){
System.out.println(e);
}
}
//线程执行结束
System.out.println("执行完毕!"+Thread.currentThread().getName());
}
}
使用匿名内部类和Lambda表达式实现线程体
package com.it_51;
public class AnonymousClass {
static Thread t1=new Thread(new Runnable() {
@Override
public void run() {
System.out.println("线程的名字:"+Thread.currentThread().getName());
}
},"匿名类创建的线程");
static Thread t2=new Thread(()->{
System.out.println("线程的名字:"+Thread.currentThread().getName());
},"Lambda表达式创建的线程");
public static void main(String[] args) {
t1.start();
t2.start();
}
}
点击链接加入群聊【程序员技术交流群】:添加链接描述