多线程初识
继承Thread类
//创建线程方式一:继承Thread类,重写run()方法,调用start开启线程
public class TestThread extends Thread{
//ctrl+o;重写run方法
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("nihao"+i);
}
}
public static void main(String[] args) {
//main线程,主线程
//创建一个线程对象
// TestThread thread = new TestThread();
// //调用start()方法开启线程
// thread.start();
new TestThread().start();
for (int i = 0; i < 500; i++) {
System.out.println("奈斯"+i);
}
}
}
实现Runnable接口
创建线程方式2;实现runnable接口,重写run方法 ,执行线程需要丢入runnable接口实现类,调用start方法
优点(比较继承Thread类):避免单线程局限性,灵活方便,方便同一个对象被多个线程使用
//推荐使用
public class TestThread01 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("nihao"+i);
}
}
public static void main(String[] args) {
new Thread(new TestThread01()).start();
}
}
练习
1 抢票
2 模拟龟兔赛跑
//多个线程同时操作同一个对象
//问题:多个线程同时操作同一个资源的情况下,线程不安全,数据紊乱
/*
小猪---拿到了第10票
小明---拿到了第10票
小猪---拿到了第9票
*/
public class TestThread02 implements Runnable{
private int ticksnums = 10;
@Override
public void run() {
while (true){
if (ticksnums<=0){
break;
}
System.out.println(Thread.currentThread().getName()+"---拿到了第"+ticksnums--+"票");
}
}
public static void main(String[] args) {
TestThread02 thread02 = new TestThread02();
new Thread(thread02,"小明").start();
new Thread(thread02,"小红").start();
new Thread(thread02,"小猪").start();
}
}
public class TestThread03 implements Runnable{
private static String winner;
@Override
public void run() {
for (int i =1 ; i <= 101; i++) {
if (Thread.currentThread().getName().equals("兔子") && i%10==0){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//判断比赛是否结束
boolean flag = gameover(i);
//如果比赛结束,停止运行
if (flag == true){
break;
}
System.out.println(Thread.currentThread().getName()+"---跑了"+i+"步");
}
}
//判断比赛是否结束
public boolean gameover(int steps){
if (winner!=null){
return true;
}{
if (steps>=100){
winner = Thread.currentThread().getName();
System.out.println("winner is "+winner);
return true;
}
}
return false;
}
public static void main(String[] args) {
TestThread03 thread03 = new TestThread03();
new Thread(thread03,"兔子").start();
new Thread(thread03,"乌龟").start();
}
}
体验多线程是并发操作
线程代理模式
/*
静态代理 总结
真实对象和代理对象都要实现同一接口
代理对象要代理真实角色
好处:代理对象可以做到真实对象做不到的事情,真实对象只需要做自己的事情
*/
public class TestThread04{
public static void main(String[] args) {
new Friend(new You()).Happy();
new Friend(new Mi()).Happy();
// Meetng mi = new Mi();
// mi = ()->{
// System.out.println("你好");
// };
// mi.Happy();
}
}
interface Meetng{
void Happy();
}
//真实对象
class You implements Meetng{
public String name = "张三";
@Override
public void Happy() {
System.out.println(name+"喝醉了,不能开车");
}
}
//真实对象
class Mi implements Meetng{
@Override
public void Happy() {
System.out.println("我喝醉了");
}
}
//代理
class Friend implements Meetng{
private Meetng target;
public Friend(Meetng target) {
this.target = target;
}
@Override
public void Happy() {
before();
this.target.Happy();
after();
}
public void before(){
System.out.println("朋友请喝酒");
}
public void after(){
System.out.println("朋友帮忙叫代驾");
}
}
Lamda 表达式
作用 :避免匿名内部类定义过多
public class TestLamdba01 {
//2静态内部类
static class Like2 implements Ilike{
@Override
public void Lamdba() {
System.out.println("I like Lamdba2");
}
}
public static void main(String[] args) {
Ilike like = new Like1();
like.Lamdba();
like = new Like2();
like.Lamdba();
//3局部内部类
class Like3 implements Ilike{
@Override
public void Lamdba() {
System.out.println("I like Lamdba3");
};
}
like = new Like3();
like.Lamdba();
//4匿名内部类 ,没有类的名字,必须借助接口(或者父类)
like = new Ilike() {
@Override
public void Lamdba() {
System.out.println("I like Lamdba4");
}
};
like.Lamdba();
//5用Lamdba简化:前提是函数式接口:只包含唯一一个抽象方法
like = ()->{
System.out.println("I like Lamdba5");
};
like.Lamdba();
}
}
interface Ilike{
void Lamdba();
//abstract void Lamdba();默认为抽象方法
}
//1实现类
class Like1 implements Ilike{
@Override
public void Lamdba() {
System.out.println("I like Lamdba1");
}
}
I like Lamdba1
I like Lamdba2
I like Lamdba3
I like Lamdba4
I like Lamdba5
多线程使用
线程停止
/*
测试stop(1)建议线程正常停止————>利用次数,不建议死循环,
(2)建议使用标志位-->设置一个标志位
(3)不要使用stop或者destroy等过时的方法
*/
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 tingzhi(){
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==990){
//3 调用方法使run---Thread线程停止
testStop.tingzhi();
System.out.println("线程该停止了");
}
}
}
}
线程睡眠
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestSleep {
public static void main(String[] args) throws InterruptedException {
// tenDown();
//打印当前系统时间
Date startTime = new Date(System.currentTimeMillis());//获取系统当前时间
while (true){
Thread.sleep(15000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
startTime = new Date(System.currentTimeMillis());//获取系统当前时间
}
}
public static void tenDown() throws InterruptedException {
int i =10;
while (true){
Thread.sleep(1000);
System.out.println(i--);
if(i <= 0){
break;
}
}
}
}
线程礼让
//测试线程礼让,不一定礼让成功,看CPU
/*
礼让线程,让当前正在执行的线程暂停,但不阻塞
将线程从运行状态转为就绪状态
*/
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();礼让
Thread.yield();
System.out.println(Thread.currentThread().getName() + "线程结束执行");
}
}
线程强行执行
join合并线程,待此线程执行完成后,在执行其他线程,其他线程阻塞——插队的意思
//测试线程礼让
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 < 1000; i++) {
System.out.println("普通用户排队"+i);
if (i == 100){
//线程礼让
thread.join();
// testjoin.run();
}
}
}
}
优先级
/*
优先级低只是意味着获得调度的概率低,并不是优先级低就不会调用了,看CPU
优先级的设置建议在start()调度前
*/
//测试优先级
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);
t1.start();
t2.setPriority(1);
t2.start();
t3.setPriority(5);
t3.start();
t4.setPriority(10);
t4.start();
t5.setPriority(Thread.MAX_PRIORITY);
t5.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
}
}
线程守护
//测试守护线程
/*
线程分为用户线程和守护线程
虚拟机必须确保用户线程执行完毕,不用等待守护线程执行完毕
*/
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);//默认是flase表示是用户线程,这里用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 <= 3600; i++) {
System.out.println("开心每一天"+i);
}
System.out.println("====good bay word====");
}
}
三大不安全及同步块
/*
synchronized方法和synchronized块
同步方法:public synchronized void method (int args){}
synchronized方法控制对象的访问,每个对象控制一把锁,每个synchronized方法
必须获得调用该方法的对象的锁才能执行
缺陷:把一个大的方法声明为synchronized 会影响效率。
*/
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket buyTicket = new BuyTicket();
new Thread(buyTicket,"小明").start();
new Thread(buyTicket,"小红").start();
new Thread(buyTicket,"小芳").start();
}
}
class BuyTicket implements Runnable{
boolean flag = true;
private int vote = 50;
@Override
public void run() {
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void buy() throws InterruptedException {
if (vote<=0){
flag = false;
return;
}else {
System.out.println(Thread.currentThread().getName()+"买到了第"+vote--+"票");
Thread.sleep(100);
}
}
}
//模拟银行取钱
/*
同步块:synchronized(Obj){}
*/
public class UnsafeBank {
public static void main(String[] args) {
Account account = new Account(1000, "家庭基金");
MyBank you = new MyBank(account,50);
MyBank girlfriend = new MyBank(account,80);
new Thread(girlfriend,"妻子").start();
new Thread(you,"丈夫").start();
}
}
//创建一个账户
class Account{
int money;
String name;
public Account(int money, String name) {
this.money = money;
this.name = name;
}
}
//创建一个银行
class MyBank implements Runnable{
Account account;
int drawingmoney; //要取的钱
int nowmoney; // 现在手里的钱
public MyBank(Account account, int drawingmoney) {
this.account = account;
this.drawingmoney = drawingmoney;
}
//取钱
@Override
public void run() {
synchronized (account){
if (account.money-drawingmoney<0){
System.out.println(Thread.currentThread().getName()+"--->你的余额没有这么多钱");
return;
}else {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额 = 余额 - 你取的钱
account.money = account.money - drawingmoney;
//你手里的钱
nowmoney = nowmoney + drawingmoney;
System.out.println(Thread.currentThread().getName()+"--->手里的钱"+nowmoney);
System.out.println(account.name+"-->余额为"+account.money);
}
}
}
}
import java.util.ArrayList;
import java.util.List;
//线程不安全的集合
public class UnsafeList {
public static void main(String[] args) throws InterruptedException {
List<String> list = new ArrayList();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
synchronized (list) {
list.add(Thread.currentThread().getName());
}
}).start();
}
Thread.sleep(10);
System.out.println(list.size());
}
}
死锁, Lock锁 ,线程池
/*
产生死锁的四个必要条件:
1,互斥条件 ;一个资源每次只能被一个进程使用
2,请求和保持条件:一个进程因请求资源阻塞时,对已获得的资源保持不放
3,不剥夺条件:进程已获得的资源,在未使用完前,不能强行剥夺
4,循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系
*/
//死锁: 多个线程互相抱着对方需要的资源,然后形成僵持
public class DeadLock {
public static void main(String[] args) {
Makeup makeup = new Makeup(0,"小红");
Makeup makeup1 = new Makeup(1,"小芳");
makeup.start();
makeup1.start();
}
}
//口红
class Lipstick{
}
//镜子
class Mirror{
}
class Makeup extends Thread{
//需要的资源只有一份,用static来保证只有一份
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choice; // 选择
String grilName;//使用的人
public Makeup(int choice, String grilName) {
this.choice = choice;
this.grilName = grilName;
}
@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.grilName+"获得口红的锁");
Thread.sleep(100);
}
synchronized (mirror){//获得镜子的锁
System.out.println(this.grilName+"获得镜子的锁");
}
}else {
synchronized (mirror){//获得镜子的锁
System.out.println(this.grilName+"获得镜子的锁");
Thread.sleep(200);
}
synchronized (lipstick){//获得口红的锁
System.out.println(this.grilName+"获得口红的锁");
}
}
}
}
/*
死锁产生
private void makeup() throws InterruptedException {
if (choice==0){
synchronized (lipstick){//获得口红的锁
System.out.println(this.grilName+"获得口红的锁");
Thread.sleep(100);
synchronized (mirror){//获得镜子的锁
System.out.println(this.grilName+"获得镜子的锁");
}}
}else {
synchronized (mirror){//获得镜子的锁
System.out.println(this.grilName+"获得镜子的锁");
Thread.sleep(200);
synchronized (lipstick){//获得口红的锁
System.out.println(this.grilName+"获得口红的锁");
}}
}
*/
import java.util.concurrent.locks.ReentrantLock;
public class TestLock implements Runnable{
private int ticksnums = 10;
//定义lock锁
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true){
lock.lock();//加锁
try {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (ticksnums>0){
System.out.println(Thread.currentThread().getName()+"---拿到了第"+ticksnums--+"票");
}else {
break;
}
} finally {
//解锁
lock.unlock();
}
}
}
public static void main(String[] args) throws InterruptedException {
TestLock testLock = new TestLock();
new Thread(testLock,"小明").start();
new Thread(testLock,"小红").start();
new Thread(testLock,"小猪").start();
}
}
线程池
◆背景:经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大。
◆思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。可以避免频繁创建销毁、实现重复利用。类似生活中的公共交通工具。
◆好处:
◆提高响应速度(减少了创建新线程的时间)
◆降低资源消耗(重复利用线程池中线程,不需要每次都创建)
◆便于线程管理(…)
◆corePoolSize:核心池的大小
◆maximumPoolSize: 最大线程数
◆keepAliveTime: 线程没有任务时最多保持多长时间后会终止
◆JDK 5.0起提供了线程池相关API: ExecutorService 和Executors
◆ExecutorService: 真正的线程池接口。常见子类ThreadPoolExecutor
◆void execute(Runnable command) :执行任务/命令,没有返回值,一般用来执行Runnable
◆ Future submit(Callable task):执行任务,有返回值,- -般又来执行Callable
◆void shutdown() :关闭连接池
◆Executors: 工具类、线程池的工厂类,用于创建并返回不同类型的线程池
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestPool {
public static void main(String[] args) {
//1,创建服务,创建线程池
//newFixedThreadPool 参数为:线程池大小
ExecutorService service = Executors.newFixedThreadPool(10);
//执行
service.execute(new MyThread("dd"));
service.execute(new MyThread("ec"));
service.execute(new MyThread("fc"));
service.execute(new MyThread("sd"));
//关闭链接
service.shutdown();
}
}
class MyThread implements Runnable{
String name;
public MyThread(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println(this.name);
}
}