进程是资源调度的最小单位。线程是CPU调度的最小单位。
线程包括,寄存器,程序计数器和 TCB, 共享进程的资源。
run 是 Thread 内部方法调用, start 创建一个新的子线程并启动。
Thread t = new Thread(new Runnable){
public void run(){
}
}
t.start()
构造函数,成员变量,回调函数(通过调用外部函数,获取数据)
public class MyThread1 extends Thread
{
private String name;
public MyThread1(String name)
{
this.name = name;
}
public void run()
{
System.out.println("hello " + name);
}
public static void main(String[] args)
{
Thread thread = new MyThread1("world");
thread.start();
}
package mythread;
public class MyThread2 implements Runnable
{
private String name;
public void setName(String name)
{
this.name = name;
}
public void run()
{
System.out.println("hello " + name);
}
public static void main(String[] args)
{
MyThread2 myThread = new MyThread2();
myThread.setName("world");
Thread thread = new Thread(myThread);
thread.start();
}
}
package mythread;
class Data
{
public int value = 0;
}
class Work
{
public void process(Data data, Integer numbers)
{
for (int n : numbers)
{
data.value += n;
}
}
}
public class MyThread3 extends Thread
{
private Work work;
public MyThread3(Work work)
{
this.work = work;
}
public void run()
{
java.util.Random random = new java.util.Random();
Data data = new Data();
int n1 = random.nextInt(1000);
int n2 = random.nextInt(2000);
int n3 = random.nextInt(3000);
work.process(data, n1, n2, n3); // 使用回调函数
System.out.println(String.valueOf(n1) + "+" + String.valueOf(n2) + "+"
+ String.valueOf(n3) + "=" + data.value);
}
public static void main(String[] args)
{
Thread thread = new MyThread3(new Work());
thread.start();
}
}
public class Main implements Runnable{
private String value;
@Override
public void run() {
try {
Thread.currentThread().sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
value = "We have data now.";
}
public static void main(String[] args) throws InterruptedException {
Main m = new Main();
Thread t = new Thread(m);
t.start();
while (m.value == null){
Thread.currentThread().sleep(100);
}
System.out.println("value: " + m.value);
}
}
t.join(), 阻塞当前线程,等待子线程执行完毕。
Callable, FutureTask Or 线程池。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
String value = "data";
System.out.println("Ready");
Thread.currentThread().sleep(3000);
System.out.println("Done");
return value;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<String> task = new FutureTask<String>(new MyCallable());
new Thread(task).start();
if (!task.isDone()) {
System.out.println("task has not finished");
}
System.out.println("task return: " + task.get());
}
}