1.介绍
不建议使用继承Tread的方法去创建多线程,java是单继承,这样可避局限性
推荐使用实现接口的方式
使用Callable创建线程
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class CallableThreadTest implements Callable<Integer>{
public static void main(String[] args)
{
CallableThreadTest ctt = new CallableThreadTest();
FutureTask<Integer> ft = new FutureTask((Callable) ctt);
for(int i = 0;i < 100;i++)
{
//输出的均为当前线程的名字
System.out.println(Thread.currentThread().getName()+" 的循环变量i的值"+i);
if(i==20)
{
new Thread(ft,"有返回值的线程").start();
}
}
try
{
System.out.println("子线程的返回值:"+ft.get());
} catch (InterruptedException e)
{
e.printStackTrace();
} catch (ExecutionException e)
{
e.printStackTrace();
}
}
@Override
public Integer call() throws Exception
{
int i = 0;
for(;i<100;i++)
{
System.out.println(Thread.currentThread().getName()+" "+i);
}
return i;
}
}
2.Lamda 表达式
3. 观测线程状态
NEW | RUNNABLE | BLOCKED | WAITING | TIMED_WAITING | TERMINATED |
Thread.start(); | 就绪状态和运行状态 | wait,io操作 read和write; | sleep,join | sleep,join | 死亡状态 |
public class TestState {
public static void main(String[] args) {
Thread thread = new Thread(() ->{
for (int i = 0; i<5;i++){
try {
Thread.sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
}
System.out.println("");
});
//观察线程状态
Thread.State state = thread.getState();
System.out.println(state);
//开启线程
thread.start();
//刷新state的值
state = thread.getState();
System.out.println(state);
while (state != Thread.State.TERMINATED){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
state = thread.getState();
System.out.println(state);
}
}
}
4.守护线程
package Tread;
public class TestShouhu {
public static void main(String[] args) {
God god = new God();
You you = new You();
//设置守护线程并启动
Thread thread = new Thread(god);
thread.setDaemon(true);
thread.start();
//启动默认线程
new Thread(you).start();
}
}
class God implements Runnable{
@Override
public void run(){
while (true){
//守护线程会随着用户线程的结束而自动结束(等一会儿守护线程才会结束)
System.out.println("守护线程……");
}
}
}
class You implements Runnable{
@Override
public void run(){
for (int i = 0;i<300;i++){
System.out.println("线程还活着");
}
System.out.println("==============线程死了==========");
}
}
5.线程同步
每个线程在自己的工作内存交互;
并发:多个线程想访问同一个对象
每个对象都有一把锁
解决并发:队列和锁
Obj是对象,锁住的是同步的资源的对象
用synchronized修饰的类,是直接把类锁了
package Tread;
import java.util.ArrayList;
import java.util.List;
public class Tongbu {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
for (int i = 0 ;i<100;i++){
new Thread(()->{
//此处是同步块,()里存放公共资源(对象)
synchronized (list){
list.add(Thread.currentThread().getName());
}
}).start();
}
try{
Thread.sleep(2000);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(list.size());
}
}
线程安全的集合 CopyOnWriteArrayList
package Tread;
import java.util.concurrent.CopyOnWriteArrayList;
public class Tongbu {
public static void main(String[] args) {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
for (int i = 0 ;i<100;i++){
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try{
Thread.sleep(2000);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(list.size());
}
}
6.死锁
死锁的四个必要条件
package Tread;
public class SiSuo {
public static void main(String[] args) {
Makeup g1 = new Makeup(0,"女孩1");
Makeup g2 = new Makeup(1,"女孩2");
g1.start();
g2.start();
}
}
//口红
class Lipstick{
}
//镜子
class Mirror{
}
class Makeup extends Thread{
//需要的资源只有一份,用Static来保证只有一份
static Lipstick lipstick= new Lipstick();
static Mirror mirror = new Mirror();
int choice;//选择
String girlName;//使用化妆品的人
Makeup(int choice,String girlName){
this.choice = choice;
this.girlName = girlName;
}
@Override
public void run(){
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//化妆,互相持有对方的锁,就是需要拿到对方的资源
private void makeup() throws InterruptedException{
if (choice == 0){
//这样会导致死锁的产生
//解决办法是:把mirror锁移出lipstick锁
synchronized (lipstick){
System.out.println(this.girlName+"获得口红的锁");
Thread.sleep(2000);
synchronized (mirror){
System.out.println(this.girlName + "获得镜子的锁");
}
}
}else{
//这样会导致死锁的产生
//解决办法是:把mirror锁移出lipstick锁
synchronized (mirror){
System.out.println(this.girlName+"获得镜子的锁");
Thread.sleep(1000);
synchronized (lipstick){
System.out.println(this.girlName+"获得口红的锁");
}
}
}
}
}
7. Lock 锁(可重入锁)
synchronized与Lock的对比
package Tread;
import java.util.concurrent.locks.ReentrantLock;
public class Lock {
public static void main(String[] args) {
TestLock2 testLock2 = new TestLock2();
new Thread(testLock2).start();
new Thread(testLock2).start();
new Thread(testLock2).start();
}
}
class TestLock2 implements Runnable{
int tickeNums = 10;
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while(true){
try {
//加锁
lock.lock();
if(tickeNums>0){
try {
Thread.sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(tickeNums--);
}else {
break;
}
}finally {
//解锁
lock.unlock();
}
}
}
}
8. 生产者与消费者
方法一:管程法
package Tread;
public class ProductorConsumer {
public static void main(String[] args) {
SynContainer container = new SynContainer();
new Productor(container).start();
new Consumer(container).start();
}
}
//生产者
class Productor extends Thread{
SynContainer container;
public Productor(SynContainer container){
this.container = container;
}
@Override
public void run() {
for (int i = 0;i<100;i++){
container.push(new Chicken(i));
System.out.println("生产了"+i+"只鸡");
}
}
}
//消费者
class Consumer extends Thread{
SynContainer container;
public Consumer (SynContainer container){
this.container = container;
}
@Override
public void run() {
for (int i = 0;i<100;i++){
System.out.println("消费了-->"+container.pop().id+"只鸡");
}
}
}
//产品
class Chicken{
int id;
public Chicken(int id){
this.id = id;
}
}
//缓冲区
class SynContainer{
Chicken[] chickens = new Chicken[10];
int count =0;
public synchronized void push(Chicken chicken){
if (count==chickens.length){
try{
this.wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
chickens[count]=chicken;
count++;
this.notifyAll();
}
public synchronized Chicken pop(){
if (count == 0){
try{
this.wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
count--;
Chicken chicken = chickens[count];
this.notifyAll();
return chicken;
}
}
方法二:信号灯法
package Tread;
public class ProductorConsumer2 {
public static void main(String[] args) {
TV tv = new TV();
new Player(tv).start();
new Watcher(tv).start();
}
}
//演员
class Player extends Thread{
TV tv;
public Player(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 Watcher extends Thread{
TV tv ;
public Watcher (TV tv){
this.tv=tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
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.notify();
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;
}
}
9.线程池
实现Runable接口创建线程池
package Tread;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class XianChengChi {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(10);
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
Future创建线程池
package Tread;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class XianChengChi_Callable {
//静态方法不能调用非静态方法,所以这里需要是静态的
public static class Tasker implements Callable<String>{
@Override
public String call() throws Exception {
return "hello";
}
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
//创建线程池并设置线程数
ExecutorService threadPool = Executors.newFixedThreadPool(3);
List<Future<String>> futures = new ArrayList<Future<String>>();
Future<String> res = null;
for(int i=0;i<5;i++){
res = threadPool.submit(new Tasker());
futures.add(res);
}
threadPool.shutdown();
for(Future<String> future:futures){
System.out.println(future.get());
}
}
}