java创建线程的方法有哪些

633
2021/4/19 10:00:48
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

java中创建线程的方法有:1.使用Runnable接口创建;2.使用Thread继承类创建;3.使用Callable和Future创建;

java创建线程的方法有哪些

java中创建线程的方法有以下几种

1.使用Runnable接口创建

public class RunnableThreadTest extends *** implements Runnable {

private int i;

public void run() {

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

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

}

}

public static void main(String[] args) {

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

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

if (i == 20) {

RunnableThreadTest rtt = new RunnableThreadTest();

new Thread(rtt, "新线程1").start();

new Thread(rtt, "新线程2").start();

}

}

}

2.使用Thread继承类创建

public class ThreadTest extends Thread {

int i = 0;

public void run() {

for (; i < 100; i++) {

System.out.println(getName() + " " + i);

}

}

public static void main(String[] args) {

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

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

if (i == 50) {

new ThreadTest().start();

new ThreadTest().start();

}

}

}

}

3.使用Callable和Future创建

public interface Callable

{

  V call() throws Exception;

}

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: java怎么创建指定日期的date类型