多线程
学习的同时,记录一下笔记,以后还会更新。
多线程简单例子入门
先看的这个,才看书。
线程的定义
在OS的定义中,进程是最小的资源分配单元,换句话说,进程是资源的占有者,如I/O,CPU等。一个进程包含一个或多个线程,线程是程序执行流的最小单元,或者说是最小的CPU调度单元,通俗的说,线程是实际的执行者。
线程共享进程的内存、寄存器等。
JAVA中几种线程的创建、阻塞
线程创建的几种方式:
- 直接继承自Thread类
public class TestThread {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Mythread();
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
if (i == 30) {
thread.start();
}
}
}
}
public class Mythread extends Thread{
@Override
public void run() {
System.out.println("in Mythread run");
for (i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
}
- 重写Runnable接口
public class TestThread {
public static void main(String[] args) throws InterruptedException {
Runnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
if (i == 30) {
thread.start();
}
}
}
}
public class MyRunnable implements Runnable{
private int i = 0;
@Override
public void run() {
System.out.println("in MyRunnable run");
for (i = 0; i < 100; i++) {
System.out.println("runnable"+Thread.currentThread().getName() + " " + i);
}
}
}
- Callable和FutureTask
public class MyCallable implements Callable<Integer> {
private int i = 0;
@Override
public Integer call() throws Exception {
int sum = 0;
for(;i<100;i++){
System.out.println(Thread.currentThread().getName() + " " + i);
sum += i;
}
return sum;
}
}
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Calltest {
public static void main(String[] args) throws InterruptedException, ExecutionException {
Callable<Integer> myCallable = new MyCallable();
FutureTask<Integer> ft = new FutureTask<Integer>(myCallable);
for(int i = 0;i<100;i++){
System.out.println(Thread.currentThread().getName() + " " + i);
if(i == 30){
Thread thread = new Thread(ft);
thread.start();
}
}
System.out.println("线程执行完毕");
int sum = ft.get();
System.out.println("sum = " + sum);
}
}