Runnable实现多线程

  • Post author:
  • Post category:其他


下面是通过实现Runnable接口的方式实现多线程的几种写法,这种方式用的相对较多,因为相对于继承Thread类的方式而言,这种方式更加灵活,解决了java单继承的痛点。

写法一:

public class ThreadTest {

public static void main(String[] args) {


new Thread(new T1()).start();

new Thread(new T2()).start();

}

}

class T1 implements Runnable{

@Override

public void run() {


for(int i = 0; i < 100; i++)

System.out.println(“T1…..running……..”);

}

}

class T2 implements Runnable{

@Override

public void run() {


for(int i = 0; i < 100; i++)

System.out.println(“T2…..running……..”);

}

}

写法二:

public class ThreadTest {

public static void main(String[] args) {


new Thread(new Runnable() {


@Override

public void run() {


for(int i = 0; i < 100; i++)

System.out.println(“T1…..running……..”);

}

}).start();

new Thread(new Runnable() {


@Override

public void run() {


for(int i = 0; i < 100; i++)

System.out.println(“T2…..running……..”);

}

}).start();

}

}

写法三:需要JDK1.8+

public class ThreadTest {

public static void main(String[] args) {


new Thread(()-> {


for(int i = 0; i < 100; i++)

System.out.println(“T1…..running……..”);

}).start();

new Thread(()-> {


for(int i = 0; i < 100; i++)

System.out.println(“T2…..running……..”);

}).start();

}

}



版权声明:本文为jinyouxinzao原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。