当前位置:首页 > 千层云服务器 > 正文

java创建线程的方法有哪些

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 System.out.println(Thread.currentThread().getName() + " " + i);

}

}

public static void main(String[] args) {

for (int i = 0; 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

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

}

}

public static void main(String[] args) {

for (int i = 0; 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;

}

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

在线客服