JAVA并发编程的书有很多,对我胃口的就这一本:《Java并发编程从入门到精通》。
不厚,但从入门讲起。
今天实践了三种线程的简单实现。
ThreadA
package demo.thread;
public class ThreadA extends Thread {
public void run() {
super.run();
try {
Thread.sleep(500L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("This is thread A.");
}
}
ThreadB
package demo.thread;
public class ThreadB implements Runnable {
public void run() {
try {
Thread.sleep(600L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("This is thread B.");
}
}
ThreadC
package demo.thread;
import java.util.concurrent.Callable;
public class ThreadC implements Callable<String> {
public String call() throws Exception {
try {
Thread.sleep(500L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("This is thread C.");
return "thread C";
}
}
ThreadMain
package demo.thread;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class ThreadMain {
public static void main(String[] args) {
ThreadA threadA = new ThreadA();
threadA.start();
ThreadB threadB = new ThreadB();
new Thread(threadB).start();
ThreadC threadC = new ThreadC();
FutureTask<String> future = new FutureTask<String>(threadC);
new Thread(future).start();
System.out.println("This is main thread.");
System.out.println("This is main thread begin.");
try {
System.out.println("threadC return value: " + future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("This is main thread end.");
}
}
输出样子
时间: 2024-10-02 08:05:25