线程的三种创建方式:继承Thread类、实现Runnable接口、实现Callable接口
自定义线程类继承Thread类,重写run()方法,编写线程执行体,创建线程对象,调用start()方法启动线程
注意:线程开启不一定立即执行,由CPU调度执行
public class TestThread1 extends Thread{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("run方法"+i);
}
}
public static void main(String[] args) {
//main主线程
//创建一个线程对象
TestThread1 testThread1 = new TestThread1();
//调用start()多条执行路径,主线程和子线程并行交替执行
testThread1.start();
//调用run()方法 只有主线程一条执行路径
//testThread1.run();
for (int i = 0; i < 10; i++) {
System.out.println("main方法"+i);
}
}
}
练习Thread,实现多线程同步下载图片:
package com.qi.thread;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
//练习Thread,实现多线程同步下载图片
public class TestThread2 extends Thread{
private String url;//网络图片地址
private String name;//保存文件名
public TestThread2(String url,String name) {
this.url = url;
this.name = name;
}
//下载图片线程的执行体
@Override
public void run() {
WebDownload webDownload = new WebDownload();
webDownload.download(url,name);
System.out.println(name+"下载成功");
}
public static void main(String[] args) {
TestThread2 t1 = new TestThread2("https://www.baidu.com/img/pc_675fe66eab33abff35a2669768c43d95.png","1.jpg");
TestThread2 t2 = new TestThread2("https://www.runoob.com/wp-content/uploads/2013/12/java.jpg","2.jpg");
TestThread2 t3 = new TestThread2("https://profile-avatar.csdnimg.cn/0416ae71c11b458b8aba7953434da7a9_ambition7786.jpg!1","3.jpg");
t1.start();
t2.start();
t3.start();
//2.jpg下载成功
//1.jpg下载成功
//3.jpg下载成功
}
}
//下载器
class WebDownload{
public void download(String url, String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常");
}
}
}
//实现Runnable接口,重写run方法,执行线程需要丢入runnable接口实现,调用start方法
public class TestThread3 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("run方法" + i);
}
}
public static void main(String[] args) {
//创建runnable接口的实现类对象
TestThread3 testThread3 = new TestThread3();
//创建线程对象,通过线程对象来开启我们的线程
Thread thread = new Thread(testThread3);
thread.start();
newThread(testThread3).start
for (int i = 0; i < 10; i++) {
System.out.println("main方法" + i);
}
}
}
package com.qi.thread;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
//练习Thread,实现多线程同步下载图片
public class TestThread4 extends Thread{
private String url;//网络图片地址
private String name;//保存文件名
public TestThread4(String url,String name) {
this.url = url;
this.name = name;
}
//下载图片线程的执行体
@Override
public void run() {
WebDownload2 webDownload2 = new WebDownload2();
webDownload2.download(url,name);
System.out.println(name+"下载成功");
}
public static void main(String[] args) {
TestThread2 t1 = new TestThread2("https://www.baidu.com/img/pc_675fe66eab33abff35a2669768c43d95.png","1.jpg");
TestThread2 t2 = new TestThread2("https://www.runoob.com/wp-content/uploads/2013/12/java.jpg","2.jpg");
TestThread2 t3 = new TestThread2("https://profile-avatar.csdnimg.cn/0416ae71c11b458b8aba7953434da7a9_ambition7786.jpg!1","3.jpg");
new Thread(t1).start();
new Thread(t2).start();
new Thread(t3).start();
}
}
//下载器
class WebDownload2{
public void download(String url, String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常");
}
}
}
package com.qi.thread;
//多个线程同时操作同一个对象,车票举例
public class TestThread5 implements Runnable{
//票数
private int tickets=10;
@Override
public void run() {
while (true){
if (tickets<=0){
break;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"拿到了第"+tickets--+"张票");
}
}
public static void main(String[] args) {
TestThread5 ticket = new TestThread5();
new Thread(ticket,"小明").start();
new Thread(ticket,"小红").start();
new Thread(ticket,"小强").start();
new Thread(ticket,"小丽").start();
// 小红拿到了第9张票
// 小强拿到了第7张票
// 小丽拿到了第10张票
// 小明拿到了第8张票
// 小明拿到了第6张票
// 小强拿到了第6张票
// 小丽拿到了第4张票
// 小红拿到了第5张票
// 小红拿到了第3张票
// 小丽拿到了第2张票
// 小明拿到了第3张票
// 小强拿到了第1张票
// 小红拿到了第0张票
}
}
package com.qi.thread;
public class Race implements Runnable{
private static String winner;
@Override
public void run() {
for (int i = 0; i <= 10; i++) {
//判断比赛是否结束
boolean flag = gameOver(i);
//如果比赛结束了就停止程序
if(flag){break;}
//模拟兔子休息
if (Thread.currentThread().getName().equals("兔") && i%3==0){
try {
Thread.sleep((long) 0.1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");
// 龟跑了0步
// 龟跑了1步
// 龟跑了2步
// 龟跑了3步
// 龟跑了4步
// 龟跑了5步
// 兔跑了0步
// 龟跑了6步
// 兔跑了1步
// 龟跑了7步
// 兔跑了2步
// 龟跑了8步
// 兔跑了3步
// 龟跑了9步
// 兔跑了4步
// winner is龟
}
}
private boolean gameOver(int steps) {
//判断是否有胜利者
if (winner != null) {//已经存在胜利者了
return true;
}{
if(steps>=10){
winner = Thread.currentThread().getName();
System.out.println("winner is"+winner);
return true;
}
}
return false;
}
public static void main(String[] args) {
Race race = new Race();
new Thread(race,"兔").start();
new Thread(race,"龟").start();
}
}
package com.qi.thread;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
//实现callable接口
public class TestCallable implements Callable<Boolean> {
private String url;
private String name;
public TestCallable(String url,String name) {
this.url=url;
this.name=name;
}
@Override
public Boolean call() {
WebDownload webDownload = new WebDownload();
webDownload.download(url,name);
System.out.println("下载了文件名为:"+name);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCallable t1 = new TestCallable("https://www.baidu.com/img/pc_675fe66eab33abff35a2669768c43d95.png", "1.jpg");
TestCallable t2 = new TestCallable("https://www.runoob.com/wp-content/uploads/2013/12/java.jpg", "2.jpg");
TestCallable t3 = new TestCallable("https://profile-avatar.csdnimg.cn/0416ae71c11b458b8aba7953434da7a9_ambition7786.jpg!1", "3.jpg");
//创建执行服务:
ExecutorService ser = Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> result1 = ser.submit(t1);
Future<Boolean> result2 = ser.submit(t2);
Future<Boolean> result3 = ser.submit(t3);
//获取结果
boolean r1 = result1.get();
boolean r2 = result2.get();
boolean r3 = result3.get();
//关闭服务
ser.shutdownNow();
}
class WebDownload{
public void download(String url, String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常");
}
}
}
}
真实对象和代理对象都要实现同一个接口
代理对象要代理真实角色
代理对象可以做很多真实对象做不了的事情,真实对象专注做自己的事情
package com.qi.staticProxy;
public class StaticProxy {
public static void main(String[] args) {
You you = new You();
new Thread( ()->System.out.println("爱")).start();
new weddingCompany(new You()).HappyMarry();
// weddingCompany weddingCompany = new weddingCompany(you);
// weddingCompany.HappyMarry();
}
}
interface Marry{
void HappyMarry();
}
//真实角色
class You implements Marry{
@Override
public void HappyMarry() {
System.out.println("要结婚了");
}
}
//代理角色
class weddingCompany implements Marry{
private Marry target;
weddingCompany(Marry target) {
this.target = target;
}
@Override
public void HappyMarry() {
before();
this.target.HappyMarry();
after();
}
private void before(){
System.out.println("结婚前");
}
private void after(){
System.out.println("结婚后");
}
}
package com.qi.Lambda;
//1定义一个函数式接口
interface ILike{
void lambda();
}
//2实现类
class Like implements ILike{
@Override
public void lambda() {
System.out.println("I Like Lambda");
}
}
//推到lambda
public class TestLambda1 {
//3静态内部类
static class Like2 implements ILike{
@Override
public void lambda() {
System.out.println("I Like lambda2");
}
}
public static void main(String[] args) {
ILike like = new Like();
like.lambda();
like = new Like2();
like.lambda();
//4局部内部类
class Like3 implements ILike{
@Override
public void lambda() {
System.out.println("I Like lambda3");
}
}
like = new Like3();
like.lambda();
//5匿名内部类,没有类的名称,必须借助接口或者父类
like = new ILike(){
@Override
public void lambda() {
System.out.println("I Like lambda4");
}
} ;
like.lambda();
//6用lambda简化
like = ()-> {
System.out.println("I Like lambda5");
};
like.lambda();
}
}
package com.qi.Lambda;
interface ILove{
void love (int a);
}
public class TestLambda2 {
public static void main(String[] args) {
ILove love = null;
// //1.lambda表示简化
// love = (int a)->{
// System.out.println("i love you" + a);
// };
// //2 简化参数类型
// love = a ->{
// System.out.println("i love you" + a);
// };
//3 简化括号
love = a -> System.out.println("i love you" + a);
love.love(1);
//
}
}
lambda表达式只能有一行代码的情况下才能简化为一行,如果有多行,那么就用代码块
前提是接口为函数是接口
多个参数也可以去掉参数类型,要去掉必须加上括号
Thread.State
package com.qi.state;
//观察测试线程的状态
public class TestState {
public static void main(String[] args) throws InterruptedException {
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);//NEW
//观察启动后
thread.start();//启动线程
state = thread.getState();
System.out.println(state);//RUNNABLE
while (state != Thread.State.TERMINATED) {
//只要线程不终止,就一直输出状态
Thread.sleep(100);
state = thread.getState();//更新线程转态
System.out.println(state);//输出状态
// NEW
// RUNNABLE
// TIMED_WAITING
// TIMED_WAITING
// TIMED_WAITING
// TIMED_WAITING
// TIMED_WAITING
// TIMED_WAITING
// //
// TERMINATED
}
}
}
方法 | 说明 |
---|---|
setPriority(int newPriority) | 更改线程的优先级 |
static void sleep(long millis) | 在指定的毫秒数内让当前正在执行的线程休眠 |
void join() | 等待该线程终止 |
static void yieId() | 暂停当前正在执行的线程对象,并执行其他线程 |
void interrupt() | 中断线程,别用这个方式 |
boolean isAlive() | 测试线程是否处于活动状态 |
package com.qi.state;
public class TestStop implements Runnable{
//1.设置一个标识位
private boolean flag = true;
@Override
public void run() {
int i = 0 ;
while (flag){
System.out.println("run...Thread"+i++);
}
}
//2.设置一个公开的方法停止线程,转换标志位
public void stop(){
this.flag=false;
}
public static void main(String[] args) {
TestStop testStop = new TestStop();
new Thread(testStop).start();
for (int i = 0; i < 100; i++) {
System.out.println("main"+i);
if (i==90){
//调用stop方法切换标志位,让线程停止
testStop.stop();
System.out.println("停止");
}
}
}
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
package com.qi.state;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestSleep {
//模拟倒计时
public static void tenDown() throws InterruptedException {
int num = 10;
while (true){
Thread.sleep(1000);
System.out.println(num--);
if (num<=0){
break;
}
}
}
public static void main(String[] args) throws InterruptedException {
// tenDown();
Date startTime = new Date(System.currentTimeMillis());//获取系统当前时间
while (true){
try {
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
startTime = new Date(System.currentTimeMillis());//更新当前时间
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
//测试线程礼让,不一定成功
public class TestYield {
public static void main(String[] args) {
MyYield myYield = new MyYield();
new Thread(myYield,"a").start();
new Thread(myYield,"b").start();
//b线程开始执行
//a线程开始执行
//b线程停止执行
//a线程停止执行
}
}
class MyYield implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"线程开始执行");
Thread.yield();//礼让
System.out.println(Thread.currentThread().getName()+"线程停止执行");
}
}
Join合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞。(插队)
package com.qi.state;
//测试join方法 (插队)
public class TestJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("线程vip"+i);
}
}
public static void main(String[] args) throws InterruptedException {
//启动线程
TestJoin testJoin = new TestJoin();
Thread thread = new Thread(testJoin);
thread.start();
//主线程
for (int i = 0; i < 500; i++) {
if (i==200){
thread.join();//插队
}
System.out.println("main"+i);
}
}
}
Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行
线程的优先级用数字表示,范围从1~10
使用一下方式改变或获取优先级
优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了。这都是看CPU的调度
package com.qi.state;
public class TestPriority {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName()+"->"+Thread.currentThread().getPriority());
MyPriority myPriority = new MyPriority();
Thread t1 = new Thread(myPriority);
Thread t2 = new Thread(myPriority);
Thread t3 = new Thread(myPriority);
Thread t4 = new Thread(myPriority);
Thread t5 = new Thread(myPriority);
Thread t6 = new Thread(myPriority);
//先设置优先级在启动
t1.start();
t2.setPriority(1);
t2.start();
t3.setPriority(4);
t3.start();
t4.setPriority(Thread.MAX_PRIORITY);
t4.start();
t5.setPriority(8);
t5.start();
t6.setPriority(7);
t6.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"->"+Thread.currentThread().getPriority());
}
}
package com.qi.state;
public class TestDaemon {
public static void main(String[] args) {
God god = new God();
You you = new You();
Thread thread = new Thread(god);
thread.setDaemon(true);//默认是false表示是用户线程,正常的线程都是用户线程
thread.start();//God守护线程启动
new Thread(you).start();//you用户线程启动
}
}
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 < 36500; i++) {
System.out.println("开心");
}
System.out.println("88");
}
}
同一个对象被多个线程同时操作(并发),处理多线程问题是,多个线程访问同一个对象,并且某些线程还想修改这个对象,这时候我们就需要线程同步,线程同步其实就是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面线程使用完毕,下一个线程在使用
由于同一进程的多个线程共享同一块存储空间,在带来方便的同事,也带来了访问冲突问题,未来保证数据在方法中被访问时的正确性,在访问时加入锁机制synchronized,当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可,存在以下问题
public synchronized void method(int args){
代码体
}
缺陷: 若将一个大的方法声明为synchronize将会影响效率
public synchronized void method(int args){
synchronized(Obj){
代码体
}
}
Obj称之为同步监视器
Obj可以是任何对象,但是推荐使用共享资源作为同步监视器
同步方法中无需指定同步监视器。因为同步方法的同步监视器就是this,就是这个对象本身,或者是class
同步监视器的执行过程
多个线程各占有一些共享资源,并且互相等待其他线程占有的资源才能运行,而导致两个或者多个线程都在等待对方释放资源,都停止执行的情形,某一个同步块同事拥有“两个以上对象的锁”时,就可能发生“死锁”的问题
上面列出了死锁的四个必要条件,我们只要想办法破其中的任意一个或多个条件就可以避免死锁发生
calss A{
//定义lock锁
private final ReentrantLock lock = new ReentrantLock();
public void m(){
lock.lock();
try{
//保证线程安全的代码
}
finally{
lock.unlock();
//如果同步代码有异常,要将unlock()写入finally语句块
}
}
}
解决线程之前通信问题的方法
方法名 | 作用 |
---|---|
wait() | 表示线程一直等待,知道其他线程通知,与sleep不同,会释放锁 |
wait(long timeout) | 指定等待的毫秒数 |
notify() | 唤醒一个处于等待状态的线程 |
notifyAll() | 唤醒同一个对象上所有调用wait()方法的线程,优先级别高的线程优先调度 |
生产者将产生好的数据放入缓冲区,消费者从缓冲区拿出数据
package com.qi.Lock;
// 生产者消费者模型->利用缓冲区解决:管程法
public class TestPC {
public static void main(String[] args) {
SynContainer container = new SynContainer();
new Product(container).start();
new Consumer(container).start();
}
}
//生产者
class Product extends Thread{
SynContainer container;
public Product(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++;
//可以通知消费者消费了
}
//消费者消费产品
public synchronized Chicken pop(){
//判断能否消费
if (count==0){
//等待费消费者生产
try{
this.wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
//如果可以消费
count--;
Chicken chicken = chickens[count];
//吃完了,通知生产者生产
return chicken;
}
}
package com.qi.Lock;
//信号灯法 标志位解决
public class TestPC2 {
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("a 节目");
}else{
this.tv.play("b 节目");
}
}
}
}
//消费者->观众
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.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;
}
}
JDK5.0起提供了线程池相关API,ExecutorService和Executors
ExecutorService:真正的线程池接口。常见子类ThreadPoolExecutor
Executors:工具类,线程池的工厂类,用于创建并返回不同类型的线程池
package com.qi.ThreadComm;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//测试线程池
public class TestPool {
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());
}
}