多线程

单词听写错误:(找不到需要的类)class not found Exception     class not found Exception    class not found Exception   class not found Exception

constructor  constructor  constructor constructor  constructor(构造函数)

线程与进程就像是孪生兄弟一样,一起出现,一起消失。同一时间一个进程可以做多个事情。我们的电脑同时处理多个任务,就是基于进程和线程。

线程是最小的运行单位,一个进程可包含多个线程。比如我们电脑可以看到70个进程,线程有1400个。线程(Thread)

实现线程:1,继承Thread类(extends Thread)  2,实现Runnable接口(implements Runnable)都需要重写run()方法。

启动线程:调用Thread类的start()方法,如果是实现接口,那么就需要Runnable1 runnable1=new Runnable1();
  Thread thread2=new Thread(runnable1); thread2.start();

线程的运行(普通线程是由CPU来决定谁先运行,不由外界影响)

1,初始化一个线程对象(new)

2,start,调用start方法,启动run方法

3,running,运行状态

4,dead,死亡状态,run方法结束。

其中running状态中可以通过调用方法来改变运行顺序。

1,睡眠状态,sleep(long millis),此方法是静态的,无返回的,睡眠时间微秒级别。

2,挂起状态,yield(),此方法是静态的,无返回的,线程显示让出CPU控制权,暂停当前正在执行的线程对象,并执行其他线程。该方法与sleep()类似,只是不能由用户指定暂停多长时间,并且yield()方法只能让同优先级的线程有执行的机会。

3,join(),等待线程终止。如果线程1中Thread2.join(),那么要等到线程2执行完成才能执行线程1.

4,Object.wait(),在其他线程调用此对象的 notify()方法或 notifyAll() 方法前,导致当前线程等待。如果出现了等待,用到notify()方法来唤醒线程。

interrupt(),中断线程。

setDaemon(),将线程设置为守护线程,他将随着主线程的死亡而死亡,不管自己是否执行完run方法。

线程的优先级是在资源紧张时,尽可能优先,不能保证百分之百的优先。setPriority(int newPriority)最高为10,最低为5,默认为5.

同步代码块,同步方法

只有在涉及到资源共享的时候才会用到(同步代码块,同步方法),而且只能在实现了Runnable类的线程中。synchronized

同步方法  :public synchronized void show(){ 共享资源(临界资源)  }

同步代码块:synchronized(Object a  /   this){共享资源(临界资源)}

同步代码块的作用更明显,下面是一个经典卖车票案例

int tickets=10;

public void run() {
  for (int i = 0; i < 2000; i++) {
  sale();
  }
 }
 //同步方法
 public synchronized void sale() {
  if (tickets > 0) {
   System.out.println(Thread.currentThread().getName() + "号窗口卖出" + tickets-- + "号票");
  }
 }

同步代码块

 int tickets=10;

public void run(){
  for(int i=0;i<10;i++){
   synchronized(this){
    if(tickets>0){
     System.out.println(Thread.currentThread().getName() + "号窗口卖出" + tickets-- + "号票");
    }
   }
  }
 }

原文地址:https://www.cnblogs.com/Kevin-Ma/p/5405916.html