May 30, 2021 Article blog
1. Inherit the Thread class to create the thread class
2. Implement the Runnable interface to create a thread class
3. Implement the Callable interface to create a thread class
Thread's implementation steps:
public class ThreadDemo extends Thread{
public void run() {
for(int i=0;i<10;i++) {
System.out.println(currentThread().getName()+":" + i);
}
}
public static void main(String args[]) {
new ThreadDemo().start();
new ThreadDemo().start();
}
}
Results:
Runnable's implementation steps:
public class RunnableDemo implements Runnable{
String threadName;
public RunnableDemo(String threadName) {
this.threadName = threadName;
}
@Override
public void run() {
for(int i=0;i<10;i++) {
System.out.println(threadName+":" + i);
}
}
public static void main(String args[]) {
new Thread(new RunnableDemo("A")).start();
new Thread(new RunnableDemo("B")).start();
}
}
Results:
The Callable interface has been available since Java5, which is an enhanced version of the Runable interface, which provides a call() method as the thread executor, the call() method can have a return value, and the call() method can declare throwing an exception.
boolean cancel(boolean may)
attempted to cancel the callable task associated with the Future.
V get()
returns the return value of the call() method in the Call task.
Calling the method becomes a thread block and you must wait until the child thread ends before you get the return value.
V get(long timeout,TimeUnit unit)
returns the return value of the call() method in the Call task.
This method allows the program to block up to the timeout and unit specified time, and if the specified time is passed, if the specified time still does not return a value, the TimeoutException exception is thrown.
boolean isCancelled()
true if the Callable task is canceled before it completes properly.
boolean isDone()
returns true if the Callable task is completed.
Runnable's implementation steps:
public class CallableDemo implements Callable<Integer> {
public static void main(String args[]) {
FutureTask<Integer> futureTask = new FutureTask<Integer>(new CallableDemo());
new Thread(futureTask).start();
try {
System.out.println("子线程返回值:" + futureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
if (futureTask.isDone()) {
System.out.println("线程结束");
}
}
@Override
public Integer call() throws Exception {
System.out.println("线程开始");
int ss = 0;
for (int i = 0; i < 20; i++) {
ss += i;
}
return ss;
}
}
Results: