多线程

多线程

下载图片


package com.atuo.less03;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.net.URL;

public class ThreadDemo1 extends Thread {
   private String url;
   private String name;

   public ThreadDemo1(String url, String name) {
       this.url = url;
       this.name = name;
  }

   @Override
   public void run() {
       WebDownloader webDownloader = new WebDownloader();
       webDownloader.downloader(url,name);
       System.out.println("我下载完了");
  }

   public static void main(String[] args) {
       ThreadDemo1 t1 = new ThreadDemo1("https://i0.hdslb.com/bfs/sycp/creative_img/202111/23f6f62d3676ccfb770a50de8c3ebf24.jpg@.webp", "24.jpg");
       t1.start();
  }
}

//下载器
class WebDownloader{
   //下载方法
   public void downloader(String url, String name){
       try {
           FileUtils.copyURLToFile(new URL(url),new File(name));
      } catch (Exception e) {
           e.printStackTrace();
      }
  }
}

Runnable接口


package com.atuo.less03;

public class Thread3 implements Runnable {
   private String name;
   private String sex;
   /**
    * When an object implementing interface <code>Runnable</code> is used
    * to create a thread, starting the thread causes the object's
    * <code>run</code> method to be called in that separately executing
    * thread.
    * <p>
    * The general contract of the method <code>run</code> is that it may
    * take any action whatsoever.
    *
    * @see Thread#run()
    */
   @Override
   public void run() {
       System.out.println(name+sex);
  }

   public static void main(String[] args) {
       Thread3 t1 = new Thread3("12","14");
       Thread thread = new Thread(t1);
       thread.start();

  }

   public Thread3(String name, String sex) {
       this.name = name;
       this.sex = sex;
  }
}

初识并发问题


package com.atuo.less03;

public class Thread4 implements Runnable {
   int ticketNums = 10;
   /**
    * When an object implementing interface <code>Runnable</code> is used
    * to create a thread, starting the thread causes the object's
    * <code>run</code> method to be called in that separately executing
    * thread.
    * <p>
    * The general contract of the method <code>run</code> is that it may
    * take any action whatsoever.
    *
    * @see Thread#run()
    */
   @Override
   public void run() {
       while (true){
           try {
               Thread.sleep(200);
          } catch (InterruptedException e) {
               e.printStackTrace();
          }
           if (ticketNums <= 0){
               break;
          }
           System.out.println(Thread.currentThread().getName()+"获得了第"+ticketNums+"张票");
           ticketNums = ticketNums - 1;
      }
  }

   public static void main(String[] args) {
       Thread4 t = new Thread4();
       Thread t1 = new Thread(t,"小明");
       Thread t2 = new Thread(t,"小红");
       Thread t3 = new Thread(t,"hello");
       Thread t4 = new Thread(t,"hel");
       t1.start();
       t2.start();
       t3.start();
       t4.start();
  }

}

静态代理


package com.atuo.less01;

public class StatisPoxy {
   public static void main(String[] args) {
       You you = new You();
       WeddingCompany weddingCompany = new WeddingCompany(you);
       weddingCompany.HapperMarry();
  }


}

interface Marry{
   void HapperMarry();
}

//一个真实的你
class You implements Marry{

   @Override
   public void HapperMarry() {
       System.out.println("我要结婚了,超开心");
  }
}

//一个虚假的
class WeddingCompany implements Marry{

   private Marry target;

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

   @Override
   public void HapperMarry() {
       before();
       this.target.HapperMarry();
       after();
  }

   private void after() {
       System.out.println("该交钱了");
  }

   private void before() {
       System.out.println("超开心");
  }
}

lamda表达式


package com.atuo.less02;

public class TestLamda {
   public static void main(String[] args) {
       Ilove love = () -> System.out.println("hello");
       love.Love();
  }
}

interface Ilove{
   void Love();
}

抽象类中只能有一个构造方法

线程停止


package com.atuo.less02;

public class TestStop implements Runnable {
    Boolean flag = true;

   /**
    * When an object implementing interface <code>Runnable</code> is used
    * to create a thread, starting the thread causes the object's
    * <code>run</code> method to be called in that separately executing
    * thread.
    * <p>
    * The general contract of the method <code>run</code> is that it may
    * take any action whatsoever.
    *
    * @see Thread#run()
    */
   @Override
   public void run() {
       int i = 0;
       while (flag){
           System.out.println("run...Thread"+i++);
      }

  }

   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 == 500){
               testStop.Stop();
          }
      }
  }
}

线程休眠


package com.atuo.less02;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.SimpleFormatter;

public class TestSleep {


   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();
          }
      }
  }

}

观察线程的状态


package com.atuo.less02;

//观察线程的状态
public class ThreadState {
   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);//Run

       while ( state != Thread.State.TERMINATED){
           state = thread.getState();
           Thread.sleep(100);
           System.out.println(state);
      }

  }
}

优先级


package com.atuo.less02;

public class ThreadProiority {
   public static void main(String[] args) {
       Test test = new Test();
       Thread t1 = new Thread(test);
       Thread t2 = new Thread(test);
       Thread t3 = new Thread(test);
       Thread t4 = new Thread(test);
       t1.setPriority(1);
       t1.start();
       t2.setPriority(7);
       t2.start();
       t3.setPriority(4);
       t3.start();
       t4.setPriority(9);
       t4.start();

  }
}

class Test implements Runnable{

   /**
    * When an object implementing interface <code>Runnable</code> is used
    * to create a thread, starting the thread causes the object's
    * <code>run</code> method to be called in that separately executing
    * thread.
    * <p>
    * The general contract of the method <code>run</code> is that it may
    * take any action whatsoever.
    *
    * @see Thread#run()
    */
   @Override
   public void run() {
       System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
  }
}

买票


package com.atuo.less02;

public class BuyTicket implements Runnable{

   int TickNums = 10;
   Boolean flag = true;

   //不安全买票
   public static void main(String[] args) {
       BuyTicket buyTicket = new BuyTicket();
       Thread t1 = new Thread(buyTicket,"苦逼的我");
       Thread t2 = new Thread(buyTicket,"牛逼的我");
       Thread t3 = new Thread(buyTicket,"可恶的黄牛党");
       t1.start();
       t2.start();
       t3.start();
  }

   /**
    * When an object implementing interface <code>Runnable</code> is used
    * to create a thread, starting the thread causes the object's
    * <code>run</code> method to be called in that separately executing
    * thread.
    * <p>
    * The general contract of the method <code>run</code> is that it may
    * take any action whatsoever.
    *
    * @see Thread#run()
    */
   @Override
   public void run() {
       while (flag){
           try {
               buy();
          } catch (InterruptedException e) {
               e.printStackTrace();
          }
      }
  }

   private synchronized void buy() throws InterruptedException {
       if (TickNums <= 0){
           flag = false;
           return;
      }
       Thread.sleep(1000);
       System.out.println(Thread.currentThread().getName()+"拿到"+TickNums--);
  }
}

管程法


package com.atuo.less03;

public class TestPC{
   public static void main(String[] args) {
       Cache cache = new Cache();
       Producer producer = new Producer(cache);
       producer.start();
       Consumer consumer = new Consumer(cache);
       consumer.start();

  }

}

class Producer extends Thread{
   Cache cache;
   public Producer(Cache cache){
       this.cache = cache;
  }
   @Override
   public void run() {
       for (int i = 0; i < 500; i++) {
           cache.push(new Chicken(i));
           System.out.println("生产了"+i+"只鸡");
      }
  }
}

class Consumer extends Thread{
   Cache cache;
   public Consumer(Cache cache){
       this.cache = cache;
  }
   @Override
   public void run() {
       for (int i = 0; i < 500; i++) {
           Chicken pop = cache.pop();
           System.out.println("消费者消费了第"+pop.getId()+"只鸡");
      }
  }
}

class Chicken{
   public int getId() {
       return id;
  }

   public void setId(int id) {
       this.id = id;
  }

   private int id;

   public Chicken() {
  }

   public Chicken(int id) {
       this.id = id;
  }
}

class Cache{
   public Cache() {
  }

   Chicken[] chickens = new Chicken[10];
   int count = 0;

   public Cache(Chicken[] chickens, int count) {
       this.chickens = chickens;
       this.count = count;
  }

   public synchronized void push(Chicken chicken){
       if (chickens.length == count){
           //等待消费这消费
           try {
               this.wait();
          } catch (InterruptedException e) {
               e.printStackTrace();
          }
      }
       chickens[count] = chicken;
       count++;
       this.notifyAll();
  }

   public synchronized Chicken pop(){
       if (count == 0){
           //生产者生产
           try {
               this.wait();
          } catch (InterruptedException e) {
               e.printStackTrace();
          }
      }
       count--;
       Chicken chicken = chickens[count];
       this.notifyAll();
       return chicken;
  }

}

线程池


package com.atuo.less03;

import java.util.concurrent.Executor;
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{

   /**
    * When an object implementing interface <code>Runnable</code> is used
    * to create a thread, starting the thread causes the object's
    * <code>run</code> method to be called in that separately executing
    * thread.
    * <p>
    * The general contract of the method <code>run</code> is that it may
    * take any action whatsoever.
    *
    * @see Thread#run()
    */
   @Override
   public void run() {
       for (int i = 0; i < 10; i++) {
           System.out.println(i);
      }
  }
}

 

posted @ 2022-04-08 22:19  亚托克斯的泯灭  阅读(60)  评论(0)    收藏  举报