Java多线程
进程和线程的的概念
进程:一个程序启动一直到它关闭,这个动态的过程我们称之为进程
线程:一个进程能同时执行一个或多个任务,我们称同时执行的任务为多线程。
实现多线程的三种方法
继承Thread类
一共三步:①继承Thread类
②重写run方法
③调用start方法
public class Thread01 extends Thread{
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("run方法 "+i);
}
}
public static void main(String[] args) {
Thread01 thread01 = new Thread01();
/*
调用run方法和start方法的区别:
调用run方法,本质是单线程快速切换运行两个任务
调用start方法,就是启用两个线程,main线程完成它的任务,start线程完成它的任务。
*/
thread01.start();
for (int i = 0; i < 30; i++) {
System.out.println("mani方法 "+i);
}
}
}
实现Runnable接口
现实Runnable接口,方便多线程执行同一对象
/*
*
* 方法二:(常用)通过实现Runnable接口 来实现多线程
*
* 一共三步:①实现Runnable接口
* ②重写run方法
* ③新建一个实现Runnable接口的类的对象,然后在新建一个Thread对象,把新建对象传进去,最后在调用start方法。
*
* */
public class Runnable01 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("runnable接口方法 "+i);
}
}
public static void main(String[] args) {
Runnable01 runnable01 = new Runnable01();
new Thread(runnable01).start();
for (int i = 0; i < 30; i++) {
System.out.println("main方法 "+i);
}
}
}
实现Callable接口(不常用)
线程并发
同一个对象被多个线程同时调用,多个线程就会争抢同一个资源,这就是并发问题。
Lambda表达式
Lambda表达式,是一种简洁快速实现类的方式,前提是重写函数式接口(只有一个方法的接口)
线程的五种状态
新生、就绪、运行、堵塞(就是让线程休眠)、死亡
线程停止
public class StopThread implements Runnable {
/*
*
*练习线程的停止,
* 用标志位的方式停止线程
*
*
* */
private boolean flag=true;//设置一个标志位
@Override
public void run() {
int i=0;
while (flag){//改变它的结果,它会一直循环
System.out.println("线程开始了-----"+i++);
}
}
public void stop(){
this.flag=false;
}
public static void main(String[] args) {
StopThread stopThread = new StopThread();
new Thread(stopThread).start();
for (int i = 0; i < 1000; i++) {
System.out.println("主线程启动了"+i);
if(i==900){
stopThread.stop();
System.out.println("副线程停止了");
}
}
}
}
线程休眠
1000ms=1s
public class SleepThread {
/*
* 练习线程休眠
*
* */
public static void main(String[] args) throws InterruptedException {
count();
}
//利用休眠倒计时
public static void count() throws InterruptedException {
int a=10;
while (true){
Thread.sleep(1000);
System.out.println(a--);
if (a==0){
break;
}
}
}
}
线程礼让
通过线程礼让,让运行的线程重新回到就绪状态
public class Yield implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"开始执行");
Thread.yield();
System.out.println(Thread.currentThread().getName()+"结束执行");
}
public static void main(String[] args) {
Yield yield = new Yield();
new Thread(yield,"a").start();
new Thread(yield,"b").start();
}
}
线程强制执行(vip)
public class Join 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 {
Join join = new Join();
Thread thread = new Thread(join);//代理模式,让thread的功能代理join的功能
thread.start();
for (int i = 0; i < 100; i++) {
System.out.println("main"+i);
if(i==50){
thread.join();
}
}
}
}
线程的检测
getState方法得到线程的状态
public class Lambda03 {
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("*****");
});
//线程检测,通过getState得到线程的状态
Thread.State state = thread.getState();
System.out.println(state);//现在是新生状态
thread.start();//启动线程,然后是运行状态
state=thread.getState();
System.out.println(state);
}
}
线程的优先级
通过设置线程的优先级来决定大概率谁先运行,(不一定准,只是让大概率优先级高的先运行)
public class Mean implements Runnable {
/*
* 设置线程的优先级
*
* */
@Override
public void run() {
//getPriority 得到线程优先级
System.out.println(Thread.currentThread().getName()+"线程优先级"+Thread.currentThread().getPriority());
}
public static void main(String[] args) {
Mean mean = new Mean();
System.out.println("main"+Thread.currentThread().getPriority());
Thread thread1 = new Thread(mean);
Thread thread2 = new Thread(mean);
Thread thread3 = new Thread(mean);
Thread thread4 = new Thread(mean);
Thread thread5 = new Thread(mean);
Thread thread6 = new Thread(mean);
thread1.setPriority(1);
thread1.start();
thread2.setPriority(8);
thread2.start();
thread3.setPriority(7);
thread3.start();
thread4.setPriority(4);
thread4.start();
thread5.setPriority(3);
thread5.start();
thread6.setPriority(10);
thread6.start();
System.out.println("main"+Thread.currentThread().getPriority());
}
}
线程守护
线程分为:用户线程和守护线程。
虚拟机必须保证用户线程执行完毕,而不用等待守护线程完毕,所以用户线程完毕守护线程自动完毕。
/**
*
*测试守护线程,需要创建一个守护线程和一个用户线程
*
* **/
public class Daemon implements Runnable { //创建一个守护线程
@Override
public void run() {
int i=0;
while (true)
System.out.println("守护线程"+i++);
}
}
class you implements Runnable{//创建一个用户线程
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("快乐努力每一天"+i);
}
System.out.println("goodbye world!");
}
public static void main(String[] args) {
Daemon daemon = new Daemon();
you you = new you();
Thread thread = new Thread(daemon);
thread.setDaemon(true); //设置守护线程
thread.start(); //启动线程
new Thread(you).start();
}
}
线程同步
当多个线程访问同一个对象,会出现并发问题,那么怎么解决呢?
那么就使用线程同步,线程同步是通过队列加锁的方式实现的,当多个线程访问同一个对象的时候会让他们进行排队,依次访问,并且让访问者上锁保证安全访问。
线程不安全案例
三个人同时买票,可能导致票为负数
/*
* 测试多个线程访问同一个资源,会出现并发问题,(既每个人抢到了同一张票)
*
* */
public class BuyTicket implements Runnable {
@Override
public void run() {
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
boolean flag=true;
int ticketNum=10;
public void buy() throws InterruptedException { //买票
while (ticketNum<=0){
flag=false;
}
Thread.sleep(300);
System.out.println(Thread.currentThread().getName()+"买了第"+ticketNum--+"张票");
}
}
class a{
public static void main(String[] args) {
BuyTicket buyTicket = new BuyTicket();
new Thread(buyTicket,"zhangshan").start();
new Thread(buyTicket,"lisi").start();
new Thread(buyTicket,"wangwu").start();
}
}
使用synchronized关键字使线程同步
synchronized关键字:1. synchronized方法(修饰在方法后面)
2. synchronized(){ 代码块 }(里面为需要同步的代码块)为增删改除的代码。
public class BuyTicket implements Runnable {
@Override
public void run() {
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
try { //在运行的程序里面加入休眠,不然第一个人会把票抢光
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
boolean flag=true;
int ticketNum=10;
public synchronized void buy() throws InterruptedException { //买票
while (ticketNum<=0){
flag=false;
return;
}
System.out.println(Thread.currentThread().getName()+"买了第"+ticketNum--+"张票");
}
}
class a{
public static void main(String[] args) {
BuyTicket buyTicket = new BuyTicket();
new Thread(buyTicket,"zhangshan").start();
new Thread(buyTicket,"lisi").start();
new Thread(buyTicket,"wangwu").start();
}
}
死锁
当两个线程同时锁死对方需要资源,而同时又等着对方释放,这种情况称为死锁。
//死锁例子
public class DeadLook {
public static void main(String[] args) {
Makeup makeup0=new Makeup(0,"小红");
Makeup makeup1=new Makeup(1,"小白");
makeup0.start();
makeup1.start();
}
}
//新建一个口红
class Lipstick{
}
//新建一个镜子
class mirror{
}
//化妆
class Makeup extends Thread{
@Override
public void run() {
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//用static来保证只有一份资源
static Lipstick lipstick= new Lipstick();
static mirror mirror = new mirror();
int choice;
String girlName;
public Makeup(int choice, String girlName) {
this.choice = choice;
this.girlName = girlName;
}
//化妆,互相持有对方的锁
private void makeup() throws InterruptedException {
if (choice==0){
synchronized (lipstick){
System.out.println(this.girlName+"获得了口红的锁");
Thread.sleep(1000);
synchronized (mirror){
System.out.println(this.girlName+"获得了镜子的锁");
}
}
}else {
synchronized (mirror){
System.out.println(this.girlName+"获得了镜子的锁");
Thread.sleep(1000);
synchronized (lipstick){
System.out.println(this.girlName+"获得了口红的锁");
}
}
}
}
}
Lock锁
通过ReentrantLock 类实现Lock锁,通过Lock进行手动加锁解锁
线程通信
通过让线程等待,让另一个线程通知它启动,这样的互动方式成为线程通信。wait方法进行等待,notifyAll通知启动
10万+

被折叠的 条评论
为什么被折叠?



