public class ThreadDemo extends Thread {
@Override
public void run() {
System.out.println("继承Thread类");
}
public static void main(String[] args) {
ThreadDemo threadDemo = new ThreadDemo();
threadDemo.start();
}
}
public class RunnableDemo implements Runnable {
@Override
public void run() {
System.out.println("实现Runnable接口");
}
public static void main(String[] args) {
Thread thread = new Thread(new RunnableDemo());
thread.start();
}
}
public class CallableDemo implements Callable<String> {
@Override
public String call() throws Exception {
return "实现Callable接口";
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<String> futureTask = new FutureTask<>(new CallableDemo());
new Thread(futureTask).start();
System.out.println(futureTask.get());
}
}
public class ThreadControlDemo {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
public class ThreadControlDemo {
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
Thread.yield();
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
});
thread1.start();
thread2.start();
}
}
public class ThreadControlDemo {
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
});
thread1.start();
try {
// 等待线程1终止,才轮到线程2
thread1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
thread2.start();
}
}