liujian-2498065510

 

多线程

多线程的创建

1. extends Thread

 class MyThread extends Thread{
     @Override
     void run(){
        ...
    }
 }
 
 class Test{
    public static void main(String[] args){
        MyThread thread = new MyThread();
        thread.start();
    }
 }

 

2. implements Runnable

 class MyThread implements Runnable{
     @Override
     void run(){
        ...
    }
 }
 
 class Test{
    public static void main(String[] args){
        MyThread thread = new MyThread();
         new Thread(thread).start();
    }
 }

 

3. 两者优劣比较

一般情况下用implements Runnable比较容易实现资源共享,我比较喜欢用这种方式创建多线程。

其实还有一种方法就是实现Callable接口。这个我不太熟。

 

 

 

 

 

多线程Thread类的一些其他属性和方法

setName和getName

 Thread.currentThread().getName(); //获取当前线程的名字
 Thread.currentThread().setName(); //设置当前线程的名字

 

setPriority和getPriority

 public class TestPriority implements  Runnable{
 
     @Override
     public void run() {
         System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
    }
     public static void main(String[] args) {
         System.out.println("main Priority"+Thread.currentThread().getPriority());
         TestPriority testPriority = new TestPriority();
         Thread t1 = new Thread(testPriority);
         Thread t2 = new Thread(testPriority);
         Thread t3 = new Thread(testPriority);
         Thread t4 = new Thread(testPriority);
         Thread t5 = new Thread(testPriority);
         System.out.println(t1.getPriority());
         t2.setPriority(7);
         t3.setPriority(10);
         t4.setPriority(3);
         t5.setPriority(1);
         t1.start();
         t2.start();
         t3.start();
         t4.start();
         t5.start();
 
    }
 }

 

join

 public class TestJion implements Runnable{
     @Override
     public void run() {
 
         for (int i = 0; i < 100; i++) {
             System.out.println("vip来了"+i);
        }
 ​    }
     public static void main(String[] args) {
         TestJion testJion = new TestJion();
         Thread thread = new Thread(testJion);
         thread.start();
         for (int i = 0; i < 500; i++) {
             System.out.println("main"+i);
             if(i==100){
                 try {
                     thread.join();
                } catch (InterruptedException e) {
                     e.printStackTrace();
                }
            }
        }
 
    }
 }

插队行为

 

sleep

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

一般用来放大线程之间的竞争关系

 

 

 

多线程中的状态

  • NEW

  • RUNNABLE

  • TIMED_WAITING

  • TERMINATED

 public class TestState {
 
     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("///////////");
        });
         Thread.State state = thread.getState();
         System.out.println(state);
         thread.start();
         state = thread.getState();
         System.out.println(state);
         while(state!=Thread.State.TERMINATED){
             try {
                 Thread.sleep(100);
            } catch (InterruptedException e) {
                 e.printStackTrace();
            }
             state=thread.getState();
             System.out.println(state);
 
        }
    }
 }
  • 补充:BLOCKED,WAITING

 

 

多线程中并发问题的处理

1. synchronized

 synchronized public class UnSafeBank  {
     public static void main(String[] args) {
         Account account = new Account("结婚基金",1000);
         Drawing you = new Drawing(account,50,"you");
         Drawing girlFriend = new Drawing(account,100,"girlFriend");
         Drawing you_2=new Drawing(account,50,"you");
         you.start();
         girlFriend.start();
         you_2.start();
    }
 }
 class Account {
     String name;
     int accountMoney;
 
     public Account(String name, int accountMoney) {
         this.name = name;
         this.accountMoney = accountMoney;
    }
 }
 
 
 class Drawing extends Thread{
 
      Account account;
      int drawMoney;
      int nowMoney;
 
     public Drawing(Account account, int drawMoney,String name) {
         this.account = account;
         this.drawMoney = drawMoney;
         this.setName(name);
    }
 
     @Override
     public void run() {
 
         synchronized (account){
 
             if(account.accountMoney-drawMoney<0){
                 System.out.println(this.getName()+"钱不够");
                 return;
            }
             try {
                 Thread.sleep(1000);
            } catch (InterruptedException e) {
                 e.printStackTrace();
            }
             account.accountMoney-=drawMoney;
             nowMoney+=drawMoney;
             System.out.println(this.getName()+"手里的钱"+nowMoney);
             System.out.println(account.name+"余额为"+account.accountMoney);
 
        }
 
 
 
    }
 }

这里的synchronized应该锁住的是account对象,而不是Drawing类中的run方法。

synchronized有两种方法:

  1. 放在类方法的返回值前,表示锁住了this对象

  2. synchronized(obj),锁住被共享的数据对象,只有当一个线程操作完了再释放。

 

 

2. lock

 public class BuyTicket implements Runnable{
     int tickets=20;
     boolean flag=true;
     private  final ReentrantLock lock = new ReentrantLock();
     @Override
     public void run() {
         lock.lock();
         try{
             while(flag){
                 try {
                     Thread.sleep(100);
                } catch (InterruptedException e) {
                     e.printStackTrace();
                }
                 buy();
            }
        }finally {
                 lock.unlock();
            }
    }
     private  void buy() {
         lock.lock();
         try{
             if(tickets<=0){
                 flag=false;
            }else{
                 System.out.println(Thread.currentThread().getName()+"买了第"+tickets--+"票");
            }
        }finally {
             lock.unlock();
        }
    }
     public static void main(String[] args) {
         BuyTicket buyTicket = new BuyTicket();
         new Thread(buyTicket,"WBC").start();
         new Thread(buyTicket,"LJ").start();
         new Thread(buyTicket,"ZGQ").start();
 
    }
 }

在Runnable实现类里面加一把锁private final ReentrantLock lock = new ReentrantLock();

在需要锁的方法里,加入lock.lock();然后用try{}把其他代码塞到大括号里面,最后finally{lock.unlock();}解锁

 

线程通信基础:生产者消费者模式

1. 一对一

 public class Main {
     public static void main(String[] args) {
         Breakfast breakfast = new Breakfast();
         new Thread(new Producer(breakfast)).start();
         new Thread(new Consumer(breakfast)).start();
    }
 }
 
 class Producer implements Runnable{
 
     private Breakfast breakfast;
 
     public Producer(Breakfast breakfast) {
         this.breakfast = breakfast;
    }
 
     @Override
     public void run() {
         int i = 7;
         for (int i1 = 0; i1 < i; i1++) {
             if (i1 %2 == 0){
                 this.breakfast.makeBreakfast("馒头","豆浆");
            }else {
                 this.breakfast.makeBreakfast("面包","冷饮");
            }
        }
    }
 }
 
 class Consumer implements Runnable{
     private Breakfast breakfast;
 
     public Consumer(Breakfast breakfast) {
         this.breakfast = breakfast;
    }
 
     @Override
     public void run() {
         int i = 7;
         for (int i1 = 0; i1 < i; i1++) {
             System.out.println("星期"+(i1+1)+"---消费者要来吃东西了");
             this.breakfast.eatBreakfast();
        }
    }
 }
 
 class Breakfast {
     private  String food;
 
     private  String drink;
 
     private boolean flag = false;//flag = false 表示需要生产 flag = true 表示需要消费
 
     public synchronized  void  makeBreakfast(String food,String drink){
 
         System.out.println("生产者进入--->标志值为:"+flag);
         if (flag){
             try {
                 System.out.println("make---wait()暂停,释放对象锁");
                 wait();
            } catch (InterruptedException e) {
                 e.printStackTrace();
            }
        }
 
         this.food

分类:

技术点:

相关文章:

  • 2018-04-25
  • 2018-07-21
  • 2021-08-21
  • 2021-04-01
  • 2021-10-16
  • 2021-11-08
  • 2021-11-08
  • 2021-11-12
猜你喜欢
  • 2021-11-11
  • 2021-12-03
  • 2021-11-07
  • 2021-05-20
  • 2021-12-08
  • 2021-12-28
相关资源
相似解决方案