线程开启不一定立即执行,由cpu调度
public class TestThread2 implements Runnable{
private String url;
private String name;
public TestThread2 (String url, String name) {
this.url = url;
this.name = name;
}
@Override
public void run() {
TestThread2.WebDownloader webDownloader = new TestThread2.WebDownloader();
webDownloader.downloader(url, name);
}
public static void main(String[] args) {
TestThread2 t1 = new TestThread2("url1", "name1");
TestThread2 t2 = new TestThread2("url2", "name2");
TestThread2 t3 = new TestThread2("url3", "name3");
new Thread(t1).start();
new Thread(t2).start();
new Thread(t3).start();
}
}
避免单继承局限性,灵活方便,方便同一个对象被多个线程使用
import java.util.concurrent.*;
// 1.重写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;
}
// 2.重写call方法,需要抛出异常
@Override
public Boolean call() {
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url, name);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 3.创建线程对象
TestCallable t1 = new TestCallable("url1", "name1");
TestCallable t2 = new TestCallable("url2", "name2");
TestCallable t3 = new TestCallable("url3", "name3");
// 4.创建执行服务
ExecutorService ser = Executor.newFixedThreadPool(3);
// 5.提交执行
Future<Boolean> r1 = ser.submit(t1);
Future<Boolean> r2 = ser.submit(t2);
Future<Boolean> r3 = ser.submit(t3);
// 6.获取结果
boolean ret1 = (r1).get();
boolean ret2 = (r2).get();
boolean ret3 = (r3).get();
// 7.关闭服务
ser.shutdownNow();
}
}
callable 的好处
public class Race implements Runnable{
private static String winner;
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
// 兔子休息
if (Thread.currentThread().getName().equals("兔子") && i % 10 == 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (gameOver(i)) {
break;
}
System.out.println(Thread.currentThread().getName() + "-->跑了 " + i + " 步");
}
}
private boolean gameOver(int steps) {
if (winner != null) {
return true;
} else if (steps >= 100){
winner = Thread.currentThread().getName();
System.out.println("winner is " + winner);
return true;
} else {
return false;
}
}
public static void main(String[] args) {
Race race = new Race();
new Thread(race, "兔子").start();
new Thread(race, "乌龟").start();
}
}
// output
......
乌龟-->跑了99步
winner is 乌龟
public class StaticProxy {
public static void main(String[] args) {
WeddingCompany weddingCompany = new WeddingCompany(new You());
weddingCompany.HappyMarry();
}
}
interface Marry {
void HappyMarry();
}
// 真实角色
class You implements Marry {
@Override
public void HappyMarry() {
System.out.println("marry");
}
}
// 代理角色
class WeddingCompany implements Marry {
private Marry marryTarget;
public WeddingCompany (Marry marryTarget) {
this.marryTarget = marryTarget;
}
@Override
public void HappyMarry() {
marryBefore();
this.marryTarget.HappyMarry();
marryAfter();
}
private void marryBefore() {
System.out.println("Layout site~");
}
private void marryAfter() {
System.out.println("Clean environment~");
}
}
函数式接口
任何接口,如果只包含唯一一个抽象方法,那么它就是一个函数式接口
public interface Runnable {
public abstract void run();
}
对于函数式接口,我们就可以通过lambda表达式来创建该接口的对象
public class TestLambda {
// 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();
}
}
// 1.定义一个接口
interface ILike {
void lambda();
}
// 2.实现类
class Like implements ILike {
@Override
public void lambda() {
System.out.println("I like lambda");
}
}
public class TestLambda2 {
public static void main(String[] args) {
// 1.lambda表达式
ILove love = (int sth)-> {
System.out.println("I love you -->" + sth);
};
love.love(1);
// 2.简化参数类型
love = (sth)-> {
System.out.println("I love you -->" + sth);
};
love.love(2);
// 3.简化括号
love = sth-> {
System.out.println("I love you -->" + sth);
};
love.love(3);
// 4.简化大括号(代码只有1行)
love = sth-> System.out.println("I love you -->" + sth);
love.love(4);
}
}
interface ILove {
void love(int sth);
}
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 < 1000; i++) {
System.out.println("main " + i);
if (i == 900) {
testStop.stop();
System.out.println("该线程停止了");
}
}
}
}
yield
public class TestYield {
public static void main(String[] args) {
MyYield myYield = new MyYield();
new Thread(myYield, "a").start();
new Thread(myYield, "b").start();
}
}
class MyYield implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "线程开始执行");
Thread.yield(); // 线程礼让
System.out.println(Thread.currentThread().getName() + "线程停止执行");
}
}
public class TestJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; 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 < 100; i++) {
if (i == 20) {
thread.join();
}
System.out.println("main " + i);
}
}
}
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();
}
}
});
// 观察状态
Thread.State state = thread.getState();
System.out.println(state); // new
// 观察启动后
thread.start(); // 启动线程
state = thread.getState();
System.out.println(state); // run
while (state != Thread.State.TERMINATED) { // 只要线程不终止,就一直输出状态
Thread.sleep(1000);
state = thread.getState(); // 更新线程状态
System.out.println(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(-1);
t5.start();
t6.setPriority(11);
t6.start();
}
}
class MyPriority implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());
}
}
// output
main-->5
Thread-0-->5
Thread-3-->10
Thread-2-->4
Thread-1-->1
Exception in thread "main" java.lang.IllegalArgumentException
at java.base/java.lang.Thread.setPriority(Thread.java:1137)
at thread.TestPriority.main(TestPriority.java:33)
优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了
// 上帝守护你
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(); // 上帝守护线程启动
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 < 36500; i++) {
System.out.println("你一生都挺开心的");
}
System.out.println("========goodbye world!========");
}
}
多个线程操作同一个资源的情况下, 线程不安全
// 多个线程操作同一个资源的情况下, 线程不安全
public class UnsafeBuyTicket implements Runnable{
private int ticketNum = 10;
boolean flag = true;
public void run() {
while (flag) {
buy();
}
}
// synchronize方法,锁的是this
private void buy() {
while (flag) {
if (ticketNum <= 0) {
flag = false;
return;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "-->拿到了第" + ticketNum-- +"票");
}
}
public static void main(String[] args) {
UnsafeBuyTicket t1 = new UnsafeBuyTicket();
new Thread(t1, "player1").start();
new Thread(t1, "player2").start();
new Thread(t1, "player3").start();
}
}
// output
player2-->拿到了第10票
player1-->拿到了第9票
player3-->拿到了第8票
player2-->拿到了第7票
player1-->拿到了第6票
player3-->拿到了第5票
player3-->拿到了第4票
player1-->拿到了第3票
player2-->拿到了第2票
player1-->拿到了第0票
player3-->拿到了第1票
player2-->拿到了第1票
public class UnsafeBank {
public static void main(String[] args) {
Account account = new Account(100, "your_money");
Drawing you = new Drawing(account,50,"you");
Drawing wife = new Drawing(account,100,"wife");
you.start();
wife.start();
}
}
// 账户
class Account {
int money;
String name;
public Account(int money, String name) {
this.money = money;
this.name = name;
}
}
// 银行
class Drawing extends Thread {
Account account; // 账户
int drawingMoney; // 取了多少钱
int curMoney; // 余额
public Drawing(Account account, int drawingMoney, String name) {
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
@Override
public void run() {
if (account.money < drawingMoney) {
System.out.println(Thread.currentThread().getName() + "钱不够,取不了");
return;
}
// 延时,让两个线程都走到这,然后继续往下
// sleep可以放大问题的发生性
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 更新余额
account.money -= drawingMoney;
curMoney += drawingMoney;
System.out.println(account.name + "余额为: " + account.money);
// this.getName() == Thread.currentThread().getName()
System.out.println(this.getName() + "手里的钱为: " + curMoney);
}
}
// output
your_money余额为: 0
wife手里的钱为: 100
your_money余额为: -50
you手里的钱为: 50
import java.util.ArrayList;
import java.util.List;
public class UnsafeList {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
// output
9993(如果是1000,说明cpu性能太好了,可以把10000调大几个数量级,即可看到现象)
缺陷
若将一个大的方法声明为synchronize方法,将会影响效率
修改上述第一个例子,买票
在buy方法前加上synchronize,即可达到预期效果
public class UnsafeBuyTicket implements Runnable{
private int ticketNum = 10;
boolean flag = true;
public void run() {
while (flag) {
buy();
}
}
// synchronize方法,锁的是this
private synchronized void buy() {
while (flag) {
if (ticketNum <= 0) {
flag = false;
return;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "-->拿到了第" + ticketNum-- +"票");
}
}
public static void main(String[] args) {
UnsafeBuyTicket t1 = new UnsafeBuyTicket();
new Thread(t1, "player1").start();
new Thread(t1, "player2").start();
new Thread(t1, "player3").start();
}
}
关于同步监视器
同步监视器的执行过程
修改上述第2个例子,取钱
在run方法内,加一个synchronize块,把需要运行的方法(可能不安全的方法)放入块内
public class UnsafeBank {
public static void main(String[] args) {
Account account = new Account(100, "your_money");
Drawing you = new Drawing(account,50,"you");
Drawing wife = new Drawing(account,100,"wife");
you.start();
wife.start();
}
}
// 账户
class Account {
int money;
String name;
public Account(int money, String name) {
this.money = money;
this.name = name;
}
}
// 银行
class Drawing extends Thread {
Account account; // 账户
int drawingMoney; // 取了多少钱
int curMoney; // 余额
public Drawing(Account account, int drawingMoney, String name) {
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
@Override
public void run() {
synchronized (account) {
if (account.money < drawingMoney) {
System.out.println(Thread.currentThread().getName() + "钱不够,取不了");
return;
}
// 延时,让两个线程都走到这,然后继续往下
// sleep可以放大问题的发生性
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 更新余额
account.money -= drawingMoney;
curMoney += drawingMoney;
System.out.println(account.name + "余额为: " + account.money);
// this.getName() == Thread.currentThread().getName()
System.out.println(this.getName() + "手里的钱为: " + curMoney);
}
}
}
import java.util.concurrent.CopyOnWriteArrayList;
// 测试JUC安全类型的集合
public class TestJUC {
public static void main(String[] args) {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
public class DeadLock {
public static void main(String[] args) {
Makeup girl1 = new Makeup(0, "girl1");
Makeup girl2 = new Makeup(0, "girl2");
girl1.start();
girl2.start();
}
}
// 口红
class LipStick {
}
// 镜子
class Mirror {
}
class Makeup extends Thread {
// static用来保证,需要用到的资源只有1份
static LipStick lipStick = new LipStick();
static Mirror mirror = new Mirror();
int choice;
String girName;
public Makeup(int choice, String girName) {
this.choice = choice;
this.girName = girName;
}
@Override
public void run() {
// 化妆
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void makeup() throws InterruptedException {
if (choice == 0) {
synchronized (lipStick) { // 获得口红的锁
System.out.println(this.girName + "获得口红的锁");
Thread.sleep(3000);
synchronized (mirror) { // 3s后获得镜子的锁
System.out.println(this.girName + "获得镜子的锁");
}
}
} else {
synchronized (mirror) { // 获得镜子的锁
System.out.println(this.girName + "获得镜子的锁");
Thread.sleep(2000);
synchronized (lipStick) { // 2s后获得口红的锁
System.out.println(this.girName + "获得口红的锁");
}
}
}
}
}
如果把上述例子的synchronize块并列放置,则不会发生死锁
用Lock锁修改上述第1个例子
import java.util.concurrent.locks.ReentrantLock;
public class TestLock {
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 {
private int ticketNum = 10;
boolean flag = true;
// 定义lock锁
private ReentrantLock lock = new ReentrantLock();
public void run() {
while (flag) {
buy();
}
}
private void buy() {
while (flag) {
try {
lock.lock(); // 加锁
if (ticketNum <= 0) {
flag = false;
return;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "-->拿到了第" + ticketNum-- +"票");
} finally {
// 解锁
lock.unlock();
}
}
}
}
// 测试生产者消费之模型-->利用缓冲区解决:管程法
public class TestPC {
public static void main(String[] args) {
SynContainer container = new SynContainer();
new Producer(container).start();
new Consumer(container).start();
}
}
// 生产者
class Producer extends Thread {
SynContainer container;
public Producer(SynContainer container) {
this.container = container;
}
// 生产方法
@Override
public void run() {
for (int i = 0; i < 100; i++) {
container.push(new Product(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 Product extends Thread {
int id;
public Product(int id) {
this.id = id;
}
}
// 缓冲区
class SynContainer {
// 产品数组缓冲区
Product[] products = new Product[10];
int count = 0;
// 生产者放入产品
public synchronized void push(Product product) {
if (count >= products.length) { // 如果缓冲区满,则等待消费者消费
// 通知消费者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 如果缓冲区不满,则将产品放入缓冲区
products[count++] = product;
// 通知消费者消费
this.notifyAll();
}
// 消费者消费产品
public synchronized Product pop(){
// 判断能否消费
if (count <= 0) { // 如果缓冲区为空,则等待生产者生产
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 如果缓冲区不空,则消费者消费
Product product = products[--count];
// 通知生产者生产
this.notifyAll();
return product;
}
}
// 测试生产者消费者问题2: 信号灯法
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("节目播放中");
} 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 {
// 演员表演,观众等待 T
// 观众观看,演员等待 F
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;
}
}
背景
由于经常需要创建、销毁、使用特别大的资源,比如并发情况下的线程,对性能影响很大
思路
可以提前创建好多个线程,放入线程池中,使用时直接获取,使用完后放回池中,可以避免频繁创建销毁、实现重复利用,类似生活中的公共交通工具
优点
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
// 测试线程池
public class TestPool {
public static void main(String[] args) {
// 1.创建服务,创建线程池
ExecutorService service = Executors.newFixedThreadPool(10);
// 执行
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
// 2.关闭连接
service.shutdownNow();
}
}
class MyThread implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}