一,线程的实现:
- 继承 Thread 类,重写runnable方法
- 实现runnable接口,实现runnable方法
- 通过Callable和FutureTask创建线程
- 通过线程池创建线程
//-- 1.继承Thread类
public class ThreadExtendsThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 30; i++) {
System.out.println("run :" + i);
}
}
public static void main(String[] args) throws InterruptedException {
System.out.println("main");
Thread thread = new ThreadExtendsThread();
thread.start();
for (int i = 'a'; i <= 'z'; i++)
System.out.println("main:" + (char) i);
}
}
//-- 2.实现runnable接口
public class ThreadImplementsRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 30; i++)
System.out.println("run :" + i);
}
public static void main(String[] args) {
Runnable runnable = new ThreadImplementsRunnable();
Thread thread2 = new Thread(runnable);
thread2.start();
for (int i = 0; i < 30; i++)
System.out.println("main:" + i);
}
}
//-- 3.callable
public class ThreadImplementCallable implements Callable<String>{
@Override
public String call() throws Exception {
System.out.println("callable....");
Thread.sleep(1000);
return "call";
}
public static void main(String[] args) throws Exception {
ThreadImplementCallable callable = new ThreadImplementCallable();
FutureTask<String> task = new FutureTask<String>(callable);
new Thread(task).start();
String str = task.get();
System.out.println(str);
}
}
//-- 4.线程池
public class Main {
public static void main(String[] args) {
ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 20, 200, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<Runnable>(5));
for (int i = 0; i < 20; i++) {
Task task = new Task(i);
executor.execute(task);
System.out.println("线程池中线程的数目:" + executor.getPoolSize() + ", 队列中等待执行的任务数目:" + executor.getQueue().size()
+ ", 已经执行完的任务数目:" + executor.getCompletedTaskCount());
}
}
}
class Task implements Runnable {
private int taskNum;
public Task(int num) {
this.taskNum = num;
}
@Override
public void run() {
System.out.println("正在执行task " + taskNum);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("task " + taskNum + "执行完毕");
}
}
二,线程的状态:
https://www.cnblogs.com/hejing-swust/p/8038263.html
- 新建 : 刚new出对象
- 可运行 :
- 运行
- 阻塞
- 死亡
三,线程的优先级:
public class ThreadPriority {
public static void main(String[] args) {
Thread ta = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("ThreadA : " + i);
}
}
});
Thread tb = new Thread(new Runnable() {
@Override
public void run() {
for (char i = 'a'; i < 'z'; i++) {
System.out.println("ThreadB : " + i);
}
}
});
ta.setPriority(10);
tb.setPriority(1);
ta.start();
tb.start();
}
}
四,线程调度:
- Thread.sleep():睡眠
- wait();
- notify();
- notifyAll();
sleep() 和 wait()的区别:
- sleep休眠,只让出cpu的使用权,任然锁住对象
- wait()让出锁,但是时间到了后会拿回锁
- sleep睡醒后不一定立即执行
- wait()使用notify或者notifyAlll或者指定睡眠时间来唤醒当前等待池中的线程。
- wiat()必须放在synchronized block中,否则会在program runtime时抛出”java.lang.IllegalMonitorStateException“异常。