了解线程

1. 多任务、进程、线程是什么?多线程

  • 当你再pc上边听歌边写博客,还挂着qq,你已经在使用多任务了。cpu会分配给不一样每一个应用不一样的时间片,它们实际上是在后台轮流执行,时间短,看着就像在同时运行同样。
  • 进程就是ctrl+alt+. 打开任务管理器以后就能看到了,一个进程由不少个线程组成;
  • 线程就是组成程序执行的最小单位了。

2. 单线程程序与多线程程序app

  • 单线程程序:你必须在听歌的时候关闭qq,不能写博客。
  • 多线程程序:同时执行多个程序

3.建立线程jvm

  • 继承Thread类<也实现了Runnable接口>
  • 实现Runnable接口(较多使用)

4.建立第一个线程ide

class MyThread extends Thread{
    public MyThread(String name){
        super(name);
    }
    @Override
    public void run() {
        for(int i=0;i<10;i++){
            System.out.println(getName()+"启动了!"); //run()里放的就是该线程要作的事情,能够被多个线程共享,就是说线程1能够去执行run
        }
    }
}
public class ThreadDemo  {

    public static void main(String[] args) {
        MyThread myThread=new MyThread("线程1");
        MyThread myThread1=new MyThread("线程2");
        myThread.start();//jVM会去调用run方法
        myThread1.start();
    }
}

经过多执行几回代码发现,线程的执行顺序是随机的,结果并不惟一。this

5.使用Runnable接口建立线程spa

class MyThread1 implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"运行了");
    }
}
public class RunnableTest {
    public static void main(String[] args) {
        MyThread1 myThread1=new MyThread1();
        Thread thread=new Thread(myThread1,"线程run");
        thread.start();        //仍是经过构造Thread对象来调用start()
    }
}
//对start()的解释
   Causes this thread to begin execution; the Java Virtual Machine * calls the
<code>run</code> method of this thread. * <p> * The result is that two threads are running concurrently: the * current thread (which returns from the call to the * <code>start</code> method) and the other thread (which executes its * <code>run</code> method). * <p> * It is never legal to start a thread more than once. * In particular, a thread may not be restarted once it has completed execution.
线程开始执行,jvm会调用线程中的run()。
结果是两个线程同时执行:当前的线程(调用start()返回的线程)和其余线程(执行run())
一个线程屡次start是不合法的。一般状况下一个线程完整执行完后不会再次start

 6.线程状态及生命周期线程

7. sleep()  和  join()3d

        sleep():app的按期刷新,定时执行。俗称:休眠rest

  join():要等调用该方法的线程执行完成后,才能执行。俗称:插队code

8. 线程的优先级  

Note:线程何时运行是不肯定的,即便设置了优先级,影响线程启动的因素不少,致使线程仍是随机启动的

//两种设置优先级的方式
thread.setPriority(10);thread.setPriority(Thread.MAX_PRIORITY);
//获取优先级
thread.getPriority(

9.线程同步

 问题:在前面咱们知道,线程的启动和中止老是随机的,不可预测。

 模拟银行取款为例,存款为一个线程,取款为一个线程。好比帐户有100元,现存进去100,有200了,再取50,剩150。

可能出现的问题是在你执行存款方法的时候,还没执行到保存的方法,线程就被取款线程取代,结果就是,帐户就剩50元。

关键字

  见另外一篇博客:

10 线程间的通讯

wait()、死锁,notify():唤醒等待的线程,notifyAll()

相关文章
相关标签/搜索