java中創建線程的方法有:1.使用Runnable接口創建;2.使用Thread繼承類創建;3.使用Callable和Future創建;
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;
}