实现runable
public class DisplayMessage implements Runnable {
public String message;
public DisplayMessage(String message) {
this.message = message;
}
@Override
public void run() {
while (true) {
System.out.println(message + Thread.currentThread().getName());
}
}
public static void main(String[] args) {
Runnable hello = new DisplayMessage("Hello");
Thread thread1 = new Thread(hello);
thread1.setDaemon(true);
thread1.setName("hello");
System.out.println("starting hello basic.thread");
thread1.start();
}
}
继承Thread
public class GuessANumber extends Thread {
public int number;
public GuessANumber(int number) {
this.number = number;
}
@Override
public void run() {
int guess = 0;
int counter = 0;
do {
guess = (int) (Math.random() * 1000 +1);
System.out.println(this.getName() + "guess" + guess);
counter ++;
} while (guess != number);
System.out.println();
}
public static void main(String[] args) {
Thread thread4 = new GuessANumber(70);
thread4.start();
}
}
实现Callable
public class CallableThreadTest implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int i = 0;
for (; i < 10; i++) {
System.out.println("" + i);
}
return i;
}
public static void main(String[] args) {
CallableThreadTest threadTest = new CallableThreadTest();
FutureTask ft = new FutureTask(threadTest);
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName());
new Thread(ft, "有返回值的线程").start();
}
try {
System.out.println("返回值:" + ft.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}