当前位置: 首页>后端>正文

多线程实现2-2:Runnable接口

多线程实现2-2:Runnable接口,第1张

/**

多线程的实现方式(二)

实现Runnable接口

1、自定义一个MyRunnable类来实现Runnable接口

2、在MyRunnable类中重写run()方法

3、创建Thread对象,并把MyRunnable对象作为Tread类构造方法的参数传递进去

4、启动线程

?*/

class MyRunnable2 implements Runnable{

????@Override

????public void run() {

????????for (int i = 0; i < 50; i++) {

????????????System.out.println(Thread.currentThread().getName() + " - " + i);

????????}

????}

????public static void main(String[] args) {

MyRunnable2 myRun = new MyRunnable2();//将一个任务提取出来,让多个线程共同去执行

//封装线程对象

Thread t01 = new Thread(myRun, "线程01");

Thread t02 = new Thread(myRun, "线程02");

Thread t03 = new Thread(myRun, "线程03");

//开启线程

????????t01.start();

????????t02.start();

????????t03.start();

//通过匿名内部类的方式创建线程

????????new Thread(new Runnable() {

????????????@Override

????????????public void run() {

????????????????for (int i = 0; i < 20; i++) {

????????????????????System.out.println(Thread.currentThread().getName() + " - " + i);

????????????????}

????????????}

},"线程04").start();

????}

}


https://www.xamrdz.com/backend/35d1941192.html

相关文章: