栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JAVA多线程

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JAVA多线程

多线程

文章目录
  • 多线程
  • 一、
    • 1.Thread
    • 2.Runnable
    • 龟兔赛跑
    • 静态代理
    • 3.Lamda表达式
    • 线程停止
    • 线程休眠
    • 倒计时 线程 sleep
    • 礼让 CUP心情 Thread.yield();
    • 强制执行join
    • 守护线程
    • synchronized
    • 多线程详解 线程非安全
    • 同步方法 synchronized
    • 死锁
    • Lock 加锁解锁
    • 线程池

–

一、

线程开启不一定立即执行,由CPU调度执行

1.Thread
public class kuang  extends  Thread{

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.print("我在打游戏");
        }
    }



    public static void main(String args[]) {

        kuang k=new kuang();
        k.start();

        for (int i = 0; i < 20; i++) {
            System.out.println("我在学习");
        }
    }

}
2.Runnable
public class kuang  implements  Runnable{

    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.print("我在打游戏");
        }
    }
    public static void main(String args[]) {

        kuang k=new kuang();
        
        Thread thread = new Thread(k);

        thread.start();
        for (int i = 0; i < 20; i++) {
            System.out.println("我在学习");
        }
    }
}


多个线程操作同一个资源的情况下,线程不安全,数据混乱

public class kuang  implements  Runnable{

private int trick=10;

    public void run() {

        while(true){
            if(trick<=0){
                break;
            }
            System.out.println(Thread.currentThread().getName()+"拿到了第"+trick--+"票");
        }
    }
    public static void main(String args[]) {
        kuang k = new kuang();
       new Thread(k, "小学生").start();
        new Thread(k, "小dsa").start();
       new Thread(k, "小老是").start();
    }
}
龟兔赛跑
public class kuang  implements  Runnable{

    private static String winner;

    public void run() {
        for (int i = 0; i <=100 ; i++) {

            if(Thread.currentThread().getName().equals("兔子")&&i%10==0){
               try {
                   Thread.sleep(5);
               }catch (InterruptedException e){
                   e.printStackTrace();
               }
            }

            boolean flag=gameover(i);
            if(flag==true){
                break;
            }

            System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");
        }

    }

    private boolean gameover(int step){
        if(winner!=null){
return  true;
        }
        {
            if (step >= 100) {
                winner = Thread.currentThread().getName();
                System.out.print("winner is" + winner);
                return true;
            }
        }
    return  false;
    }


    public static void main(String args[]) {

        kuang k=new kuang();
        new Thread(k,"兔子").start();
        new Thread(k,"乌龟").start();
    }
}
静态代理
public class kuang {
    public static void main(String args[]) {
        you y = new you();

        he h1 = new he(y);

        h1.happymary();
    }
}


    interface Marry {
        void happymary();
    }

class  you implements Marry{

    public void happymary() {
System.out.println("花喻峰要结婚了,真开心");
    }
}



class he implements  Marry {
    private Marry target;

    public he(Marry target) {
        this.target = target;
    }

    public void happymary() {
        before();
        this.target.happymary();
        after();
    }

    private void after() {
        System.out.println("结婚之后后");
    }

    private void before() {
     System.out.println("结婚之前");
    }
}
3.Lamda表达式
package kuang;
public class kuang {
//静态内部类
//   static class like2 implements llike{
//        public void lambda() {
//            System.out.println("i like lambda2");
//        }
//    }

 public static void main(String args[]) {
        llike like=new like();
        like.lambda();

//        like = ()->{
//           System.out.println("i like lambda2");
//        };
//like.lambda();
//  like=new like2();
//        like.lambda();

     //局部内部类
//     class like3 implements llike{
//         public void lambda() {
//             System.out.println("i like lambda3");
//
//             llike  like=new like3();
//             like.lambda();
//         }
//     }
//局部内部类
//             like =new llike() {
//
//                 public void lambda() {
//                     System.out.println("i like lambda4");
//                 }
//             };
//        like.lambda();
 }
}
 interface llike{
        void  lambda();
    }
 class like implements llike{
        public void lambda() {
            System.out.println("i like lambda");
        }
    }
线程停止
public class kuang  implements Runnable{

boolean flag=true;
    public void run() {
int i=0;
while(flag){
System.out.print("running"+i++);
} }

    public  void stop(){
        this.flag=false;
    }

public static void main(String[] args) {
kuang k=new kuang();

new Thread(k).start();
        for (int i = 0; i <1000 ; i++) {
            System.out.println(i);
if(i==900){
    k.stop();
    System.out.println("结束");
}
        }
    }
}
线程休眠 倒计时 线程 sleep
public class kuang   {
    public static void temDown() throws InterruptedException{
int num=10;

while(true){
Thread.sleep(1000);
    System.out.println(num--);
    if(num<=0){
        break;
    }
} 
    }
    public static void main(String[] args) {
      try{
          temDown();
      }catch (InterruptedException e){
          e.printStackTrace();
      }
    }
}
public class kuang   {

 public static void main(String[] args) {
     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(); }
}
 }
}
礼让 CUP心情 Thread.yield();

`

``java
public class kuang   {

    public static void main(String[] args) {
        kuange k=new kuange();
        new Thread(k,"a").start();
        new Thread(k,"b").start();
    }

}
class  kuange implements Runnable{
    public void run() {
        System.out.println(Thread.currentThread().getName()+"开始2");
        Thread.yield();
        System.out.println(Thread.currentThread().getName()+"停止");
    }
}
强制执行join
public class kuang implements Runnable{
    public static void main(String[] args) throws  InterruptedException{
kuang k=new kuang();
Thread thread=new Thread(k);
thread.start();

            for (int i = 0; i < 500; i++) {
                if(i==200){
          thread.join();
                }
                System.out.println("main"+i);
            }

    }

    public void run() {
        for (int i = 0; i < 1000; i++) {
System.out.println("线程VIp来了"+i);
        }
    }
}
守护线程
public class kuang{
    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
    {

        public void run() {
            while(true){
                System.out.println("上帝保护着你");
            }
        }
    }

class  You implements  Runnable{

    public void run() {
        for (int i = 0; i <100; i++) {
            System.out.println("开心的活着");
        }
        System.out.println("8888888886");
    }
}
synchronized 多线程详解 线程非安全
public class kuang{
    public static void main(String[] args) {
        Buytrick buytrick = new Buytrick();

        new Thread(buytrick,"小学生").start();
        new Thread(buytrick,"小米").start();
        new Thread(buytrick,"小是").start();
    }
}

class Buytrick implements Runnable{

    private int trick=10;
 boolean flag=true;
    public void run() {
while (flag){
    try {
        buy();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
    }

    public void buy() throws InterruptedException {
        if(trick<=0){
            flag=false;
            return;
        }
        {
            Thread.sleep(100);
            System.out.println(Thread.currentThread().getName() + "拿到" + trick--);
        }
    }
}
public class kuang{
    public static void main(String[] args) {
   Account account=new Account(100,"礼金");
   Drawing drawing=new Drawing(account,50,"你");
        Drawing drawing1=new Drawing(account,100,"你老婆");
        drawing.start();
        drawing1.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 nowMoney;

    public Drawing(    Account account,int drawingMoney, String name){
        super(name);
        this.account=account;
        this.drawingMoney=drawingMoney;
    }

    public void run(){
        if(account.money-drawingMoney<0){
            System.out.println(Thread.currentThread().getName()+"钱不够");
            return;
        }

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        account.money=account.money-drawingMoney;
        nowMoney=nowMoney+drawingMoney;
        System.out.println(account.name+"余额为"+account.money);
        System.out.println(this.getName()+"手里的钱"+nowMoney);
    }
}
同步方法 synchronized

synchronized(obj){} 增删改的对象

 public  synchronized void buy() throws InterruptedException {
        if(trick<=0){
            flag=false;
            return;
        }
        {
            Thread.sleep(100);
            System.out.println(Thread.currentThread().getName() + "拿到" + trick--);
        }
    }
}
死锁
public class kuang{
    public static void main(String[] args) {
makeup m=new makeup(0,"小红");
        makeup m2=new makeup(1,"小白");
        m.start();
        m2.start();
    }
}

class  lipstick{

}

class mirror{

}

class  makeup extends Thread{
 static lipstick l=new lipstick();
 static mirror m=new mirror();

 int choice;
 String name;
 makeup ( int choice,String name){
     this.choice=choice;
     this.name=name;
 }

 public void run(){
     try {
         makeup();
     } catch (InterruptedException e) {
         e.printStackTrace();
     }
 }

     private void makeup() throws InterruptedException {
         if (choice == 0) {
             synchronized (l) {
                 System.out.println(this.name + "获得口红");
                 Thread.sleep(100);

             synchronized (m) {
                 System.out.println(this.name + "获得镜子");

             }}
         } {
             synchronized (m) {
                 System.out.println(this.name + "获得镜子");
                 Thread.sleep(200);

             synchronized (l) {
                 System.out.println(this.name + "获得口红");

             }   }
         }
     }
}

将代码快拿出来 避免死锁

Lock 加锁解锁
public class kuang  {
    public static void main(String args[]) {
        trick k=new trick();
        new Thread(k).start();
        new Thread(k).start();
        new Thread(k).start();
    }
}
class  trick implements Runnable{
    int trick=10;

 private final   ReentrantLock lock=new ReentrantLock();

    public void run() {
        while(true){

            try {
                lock.lock();
                if(trick>0)
                {
                    try {
                        Thread.sleep(1000);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                    System.out.println(trick--);
                }else{
                    break;}
            }finally {
                lock.unlock();
            }
        }
    }
}

线程池
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/947140.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号