1.进程和线程
一个进程包含至少一个线程
java虚拟机中运行运用程序同时执行多个执行线程
Java线程:main 、Garbage Collection
2.三种创建方式
Thread class:继承Thread类(重点)
Runnable接口 :实现Runnable接口(重点※)
Callable接口:实现Callable接口(了解)
2.1Thread
自定义线程类继承Thread类
重新run()方法,编写线程执行体
创建线程对象,调用start()方法启动线程
class PrimeThread extends Thread{
long minPrime;
PrimeThread(long minPrime){
this.minPrime=minPrime;
}
public void run(){
//compute primes larger than minPrime
...
}
}
package com.fyh.thread;
public class TestThread1 extends Thread {
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("study"+i+"run");
}
}
public static void main(String[] args) {
//main线程,主线程
TestThread1 testThread1=new TestThread1();
testThread1.start();
for (int i = 0; i < 20; i++) {
System.out.println("study"+i);
}
}
}
线程抢占资源顺序是随机的,导致结果不同
子类继承Thread类具备多线程能力
启动线程:子类对象.start();
不建议使用:避免OOP单继承局限性
2.2Runnable接口
package com.fyh.thread;
public class TestThread2 extends Thread {
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("study"+i+"run");
}
}
public static void main(String[] args) {
//main线程,主线程
//创建Runnable接口的实现类对象
TestThread2 testThread2 = new TestThread2();
//创建线程对象,通过线程对象来开启我们的线程,代理
Thread thread = new Thread(testThread2);
thread.start();
//new Thread(testThread2).start();
for (int i = 0; i < 20; i++) {
System.out.println("study"+i);
}
}
}
实现接口Runnable具有多线程能力
启动线程:传入目标对象+Thread对象.start();
推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多个线程使用
都不推荐 建议使用线程池
实现Callable接口(了解即可)
1.重写Callable接口,需要返回值类型
2.重写call方法,需要抛出异常
3.创建目标对象
4.创建执行服务:ExecutorService ser=Executors.newFixedThreadPool(1);
5.提交执行:boolean r1=result1.get()
6.关闭服务:ser.shutdownNow();
并发协作模型生产者/消费者问题
1.管程法
2.信号灯法
package com.fyh.Test;
public class TestPc1 {
public static void main(String[] args) {
TV tv=new TV();
new Actor(tv).start();
new Audience(tv).start();
}
}
class Actor extends Thread{
TV tv;
public Actor(TV tv){
this.tv=tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
if (i%2==0){
this.tv.play("快乐大本营");
}else {
this.tv.play("广告");
}
}
}
}
class Audience extends Thread{
TV tv;
public Audience(TV tv){
this.tv=tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
this.tv.watch();
}
}
}
class TV{
String voice;
boolean flag=true;
public synchronized void play(String voice){
if (!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演员开始表演:"+voice);
this.notifyAll();//通知唤醒
this.voice=voice;
this.flag=!this.flag;
}
public synchronized void watch(){
if (flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观众观看了"+voice);
this.notifyAll();
this.flag=!this.flag;
}
}
线程池