Java学习日记(七)多线程

多线程

1.概念:

进程:

       是一个正在执行中的程序。每一个进程执行都有一个执行顺序,该顺序是一个执行路径或者叫一个控制单元。

线程:

       就是进程中的一个独立的控制单元,线程在控制着进程的执行。

一个进程中至少有一个线程。

比如Java VM启动的时候会有一个进程java.exe,该进程至少一个线程负责java程序的执行,而且这个线程运行的代码存在于main方法中,该线程称之为主线程。(jvm启动不止一个线程,还有负责垃圾回收机制的线程)

线程的四种状态:(如下图所示)

 

2.创建线程

问:那么该如何在自定义的代码中,自定义一个线程呢?

答:通过对API的查找,java已经提供了对线程这类事物的描述,就是Thread类。

★创建线程的第一种方式:继承Thread

步骤:

1.定义类继承Thread。

2.复写Thread类中的run方法(目的:将自定义代码存储在run方法中,让线程运行)。

3.调用线程的start方法(作用:1.启动线程;2.调用run方法)。

示例:

class Demo extends Thread {
       //覆盖run方法
       public void run() {
              for(int x = 0; x <= 20; x++) {
                     System.out.println("demo run---" + x);
              }
       }
}

class ThreadDemo {
       public static void main(String[] args) {
              //创建好一个线程
              Demo d = new Demo();
              //开启线程并执行该线程的run方法
              d.start();
              //仅仅是对象调用方法,而线程创建了,并没有运行
              //d.run();
              for(int x = 0; x <= 10; x++) {
                     System.out.println(x);
              }
       }
}

运行结果:

0

1

2

demo run---0

demo run---1

demo run---2

demo run---3

demo run---4

demo run---5

demo run---6

demo run---7

demo run---8

demo run---9

demo run---10

demo run---11

demo run---12

demo run---13

demo run---14

demo run---15

demo run---16

demo run---17

demo run---18

demo run---19

demo run---20

3

4

5

6

7

8

9

10

附注:

发现每次结果都不同。为什么呢?

因为多个线程都获取cpu的执行权,cpu执行到哪个,哪个就运行。明确一点:在某一个时刻,只能有一个程序在运行(多核除外),cpu在做着快速的切换,以达到看上去是同时运行的效果。(我们可以理解为:多线程的运行是在互相抢夺cpu的执行权)

这就是多线程的一个特性:随机性。(谁抢到谁执行,至于执行多长,cpu说的算)

问:为什么要覆盖run方法呢?

答:Thread类用于描述线程,该类就定义了一个功能,用于存储线程要运行的代码,该存储的功能就是run方法,也就是说Thread类中的run方法,用于存储线程要运行的代码。

练习:(创建两个线程,和主线程交替运行。)

原来线程都有自己默认的名称,Thread-编号 该编号从0开始。

提示:static Thread currentThread():获取当前线程对象。

         getName(): 获取线程名称。

         设置线程名称:setName或者构造函数

代码实现:

class Test extends Thread {
       Test(String name) {
              super(name);
       }
       public void run() {
              for(int x = 1; x <= 10; x++) {
                     System.out.println((Thread.currentThread()== this) + "..."+ this.getName() + "run..." + x);
              }
       }
}

class ThreadDemo {
       public static void main(String[] args) {
              Test t1 = new Test("one---");
              Test t2 = new Test("two------");
              t1.start();
              t2.start();
              for(int x = 1; x <= 10; x++) {
                     System.out.println("main......"+ x);
              }
       }
}

运行结果:

main......1

main......2

main......3

main......4

main......5

true...two------run...1

true...two------run...2

true...two------run...3

true...two------run...4

true...two------run...5

true...two------run...10

true...one---run...1

true...one---run...2

true...one---run...3

true...two------run...6

true...two------run...7

true...one---run...4

true...one---run...5

true...one---run...6

true...one---run...7

true...two------run...8

true...two------run...9

true...one---run...8

true...one---run...9

true...one---run...10

main......6

main......7

main......8

main......9

main......10

★创建线程的方式二:实现Runnable接口

步骤:

1.定义类实现Runnable接口。

2.覆盖Runnable接口中的run方法,将线程要运行的代码存放在该run方法中。

3.通过Thread类建立线程对象。

4.将Runnable接口的子类对象作为实际参数传递给Thread类的构造函数。

5.调用Thread类的start方法开启线程并调用Runnable接口子类的run方法

练习:(简单的卖票程序,多个窗口同时买票。)

代码实现:

class Ticket implements Runnable {
       private int tick = 20;
       //覆盖run方法
       publicvoid run() {
              while(true) {
                     if(tick > 0) {
                            //显示线程名及余票数
                            System.out.println(Thread.currentThread().getName()+ "...sale"+ tick--);
                     }
              }
       }
}

class ThreadDemo {
       public static void main(String[] args) {
              Ticket t=new Ticket();
              //将Ticket的子类作为实际参数传递给Thread类的构造函数
              Thread t1=new Thread(t);
              Thread t2=new Thread(t);
              Thread t3=new Thread(t);
              //调用Thread类的start方法(开启线程并调用Ticket类的run方法)
              t1.start();
              t2.start();
              t3.start();
       }
}

运行结果:

Thread-1...sale20

Thread-1...sale17

Thread-1...sale16

Thread-1...sale15

Thread-1...sale14

Thread-1...sale13

Thread-1...sale12

Thread-1...sale11

Thread-1...sale10

Thread-1...sale9

Thread-1...sale8

Thread-1...sale7

Thread-1...sale6

Thread-1...sale5

Thread-1...sale4

Thread-2...sale18

Thread-2...sale3

Thread-2...sale2

Thread-0...sale19

Thread-1...sale1

问:为什么要将Runnable接口的子类对象传递给Thread的构造函数?

答:因为自定义的run方法所属的对象是Runnable接口的子类对象,所以要让线程去指定对象的run方法,就必须明确该run方法所属的对象。

实现Runnable接口的好处:避免了单继承的局限性,在定义线程时,建议使用这种方式

总结:

已经学习了创建线程的两种方式,那两者有啥区别呢?

继承Thread:线程代码存放Thread子类run方法中

实现Runnable:线程代码存在接口的子类的run方法

3线程安全问题:

通过分析上面卖票的示例可以发现,打印出0,-1,-2等错误票数,这样多线程的运行就出现了安全问题。

导致安全问题出现的原因:

       当多条语句在操作同一个线程共享数据时,一个线程对多条语句只执行了一部分还没有执行完,另外一个线程参与进来执行,导致了共享数据的错误。

解决方法:

       对多条操作共享数据的语句,只能让一个线程都执行完,在执行过程中,其他线程不可以参与执行。

java对于多线程的安全问题提供了专业的解决方式(同步代码块):

格式:

synchronized(对象){

       需要同步的代码;

}

这个对象就如同锁,持有锁的线程可以在同步中执行;没有持有锁的线程即使获取了cpu执行权,也进不去,因为没有获取到锁

代码优化后如下所示:

class Ticket implements Runnable {
       private int tick = 4000;
       Object obj = new Object();
       //覆盖run方法
       public void run() {
              while(true) {
                     synchronized (obj) {
                            if(tick > 0) {
                                   try{
                                          //使用线程中的sleep方法,模拟线程出现的安全问题,因为sleep方法有异常声明
                                          Thread.sleep(10);
                                   }catch(Exception e){}
                                   //显示线程名及余票数
                                   System.out.println(Thread.currentThread().getName() +"...sale" + tick--);
                            }
                     }
              }
       }
}

class ThreadDemo {
       public static void main(String[] args) {
              Ticket t = new Ticket();
              //将Ticket的子类作为实际参数传递给Thread类的构造函数
              Thread t1 = new Thread(t);
              Thread t2 = new Thread(t);
              Thread t3 = new Thread(t);
              Thread t4 = new Thread(t);
              //调用Thread类的start方法(开启线程并调用Ticket类的run方法)
              t1.start();
              t2.start();
              t3.start();
              t4.start();
       }
}

注:线程安全问题在理想状态下,不容易出现,但一旦出现对软件的影响是非常大的

同步函数:

格式:在函数上加上synchronized修饰符即可。

那么同步函数用的是哪一个锁呢?

函数需要被对象调用,那么函数都有一个所属对象引用,就是this,所以同步函数使用的锁就是this。

下面就来验证:

使用两个线程来卖票,一个线程在同步代码块中,一个线程放在同步函数中,都执行买票动作。

代码如下:

class Ticket implements Runnable {
       private int tick = 1000;
       Object obj = new Object();
       boolean flag = true;
       //覆盖run方法
       public void run() {
              if(flag) {
                     while(true) {
                            synchronized(obj) {
                                   if(tick > 0) {
                                          try{
                                                 Thread.sleep(10);
                                          }catch (Exception e) {
                                          }
                                          System.out.println(Thread.currentThread().getName()+"...cold" + tick--);
                                   }
                            }
                     }
              }else {
                     while(true)
                            show();
              }
       }
       //直接在函数上用synchornized修饰符即可实现同步
       public synchronized void show() {
              if(tick > 0) {
                     try{
                            Thread.sleep(10);
                     }catch (Exception e) {
                     }
                     System.out.println(Thread.currentThread().getName()+"....show.... : " + tick--);
              }
       }
}

总结:

同步的表现形式:

       1.同步代码块

       2.同步函数

两者的区别在于:同步代码块使用的锁是任意对象,同步函数使用的锁是this。

同步的原理:就是将部分操作功能数据的代码进行加锁

同步的前提:

       1.必须要有两个或者两个以上的线程;2.必须是多个线程使用同一个锁

必须保证同步中只能有一个线程在运行

优点:解决了多线程的安全问题

弊端:多个线程需要判断锁,较为消耗资源

练习:(需求:银行有一个金库,有两个账户分别存300元,每次存100,存3次,请问程序会不会出现安全问题?该如何解决?)

分析:如果不加同步代码块或者同步函数的话,银行总账户的存入会出现两个用户同时存的时候总账没有及时相应。

加上同步后的实现代码:

class Bank {
       private int sum;
       //采用同步代码块也是可以的
       public synchronized void add(int n) {
              sum+= n;
              try{
                     Thread.sleep(10);
              }catch (Exception e) {
              }
              System.out.println(Thread.currentThread().getName()+ "sum=" + sum);
       }
}

class Cus implements Runnable {
       private Bank b = new Bank();
       public void run() {
              for(int x = 0; x < 3; x++) {
                     b.add(100);
              }
       }
}

class BankDemo {
       public static void main(String[] args) {
              Cusc = new Cus();
              Thread t1 = new Thread(c);
              Thread t2 = new Thread(c);
              t1.start();
              t2.start();
       }
}

运行结果:

Thread-0sum=100

Thread-0sum=200

Thread-1sum=300

Thread-1sum=400

Thread-1sum=500

Thread-0sum=600

问:如何寻找多线程中的安全问题?

答:1.明确哪些代码是多线程运行代码;2.明确共享数据;3.明确多线程运行代码中哪些语句是操作共享数据的

4.静态函数的同步方式

如果同步函数被静态修饰后,使用的锁又是什么呢?

通过验证,发现不在是this,因为静态方法中也不可以定义this。静态进内存是,内存中没有本类对象,但是一定有该类对应的字节码文件对象。类名.class该对象的类型是Class

class Ticket implements Runnable {
       private static int tick = 1000;
       boolean flag = true;
       //覆盖run方法
       public void run() {
              if(flag) {
                     while(true) {
                            synchronized(Ticket.class) {
                                   if(tick > 0) {
                                          try{
                                                 Thread.sleep(10);
                                          }catch (Exception e) {
                                          }
                                          System.out.println(Thread.currentThread().getName()+"...cold" + tick--);
                                  }
                            }
                     }
              }else {
                     while(true)
                            show();
              }
       }

       public static synchronized void show() {
              if(tick > 0) {
                     try{
                            Thread.sleep(10);
                     }catch (Exception e) {
                     }
                     System.out.println(Thread.currentThread().getName()+"....show.... : " + tick--);
              }
       }
}

class ThreadDemo {
       public static void main(String[] args) {
              Ticket t = new Ticket();
              //将Ticket的子类作为实际参数传递给Thread类的构造函数
              Thread t1 = new Thread(t);
              Thread t2 = new Thread(t);
              //调用Thread类的start方法(开启线程并调用Ticket类的run方法)
              t1.start();
              try{
                     Thread.sleep(10);
              }catch (Exception e) {
              }
              t.flag= false;
              t2.start();
       }
}

总结:静态的同步方法,使用的锁是该方法所在类的字节码文件对象。类名.class

附注:(加同步的单例设计模式)

代码一(饿汉式——开发常用):

class Single{
       private static final Single s = new Single();
       private single(){}
       public static Single getInstance(){
              return s;
       }
}

代码二(懒汉式——面试常考):

class Single{
       private static Single s = null;
       private Single(){}
       public static Single getInstance(){
              if(s== null){
                     synchronized(Single.class){
                            if(s== null)
                                   s= new Single();
                     }
              }
              return s;
       }
}

红色部分表示加载该类所属的字节码文件对象

补充:

饿汉式与懒汉式的区别:懒汉式特点在于实例的延迟加载,如果多线程访问会出现安全问题——加同步来解决(同步代码块和同步函数都行,有些低效),加同步时使用的锁为该类所属的字节码文件对象

5.死锁:

       同步中嵌套同步

示例:

//定义两个锁对象

class MyLock {
       staticObject locka = new Object();
       staticObject lockb = new Object();
}

//定义一个类实现Runnable
class LockTest implements Runnable {
       private boolean flag;
       LockTest(booleanflag) {
              this.flag= flag;
       }
       //覆盖run方法
       public void run() {
              if(flag) {
                     while(true) {
                            synchronized(MyLock.locka)// a锁
                            {
                                   System.out.println(Thread.currentThread().getName()+"------if_locka");
                                   synchronized(MyLock.lockb)// b锁
                                   {
                                          System.out.println(Thread.currentThread().getName()+"------if_lockb");
                                   }
                            }
                     }
              }else {
                     while(true) {
                            synchronized(MyLock.lockb)// b锁
                            {
                                   System.out.println(Thread.currentThread().getName()+"------else_lockb");
                                   synchronized(MyLock.locka)// a锁
                                   {
                                          System.out.println(Thread.currentThread().getName()+"------else_locka");
                                   }
                            }
                     }
              }
       }
}

运行结果:

……

Thread-0------if_locka

Thread-0------if_lockb

Thread-0------if_locka

Thread-1------else_lockb运行卡住了,处于死锁状态

6.线程间通信

就是多个线程在操作同一资源,但是操作的动作不同

示例:(编写一段程序:对一堆资源进行存取操作)

class Res {
       private String name;
       private String sex;
       private boolean flag = false;
       public synchronized void set(String name, String sex) {
              if(flag)
                     try{
                            //如果有资源时,等待资源取出
                            this.wait();
                     }catch (Exception e) {
                     }
              this.name= name;
              this.sex= sex;
              //表示有资源
              flag= true;
              //等待唤醒
              this.notify();
       }

       public synchronized void out() {
              if(!flag)
                     try{
                            //如果没有资源时,等待存入资源
                            this.wait();
                     }catch (Exception e) {
                     }
              System.out.println(Thread.currentThread().getName()+ name + "........"+ sex);
              //资源已经取出
              flag= false;
              //等待唤醒
              this.notify();
       }
}

// 存线程
class Input implements Runnable {
       private Res r;
       Input(Resr) {
              this.r= r;
       }
       //覆盖run方法
       public void run() {
              int x = 0;
              while(true) {
                     if(x == 0)
                            r.set("王老师", "男");
                     else
                            r.set("李小姐", "女");
                     x= (x + 1) % 2;
              }
       }
}

// 取线程
class Output implements Runnable {
       private Res r;
       Output(Resr) {
              this.r= r;
       }
       //覆盖run方法
       public void run() {
              while(true) {
                     r.out();
              }
       }
}

class ResDemo {
       public static void main(String[] args) {
              // 新建资源对象
              Res r = new Res();
              // 让存取线程同时操作同一个资源r
              new Thread(newInput(r)).start();
              new Thread(newOutput(r)).start();
       }
}

运行结果:

……

Thread-1李小姐........

Thread-1王老师........

Thread-1李小姐........

Thread-1王老师........

Thread-1李小姐........

Thread-1王老师........

Thread-1李小姐........

……

思考:wait()、notify()、notifyAll()用来操作线程为什么定义在了Object类中?

       1.这些方法存在于同步中(因为要对持有监视器(锁)的线程操作);

       2.使用这些方法时必须要标识所属的同步的锁;

       3.锁可以是任意对象,所以任意对象调用的方法一定定义在Object类中。

思考:wait()、sleep()有什么区别?

       wait():释放cpu执行权,释放锁;

       sleep():释放cpu执行权,不释放锁。

注意:只有同一个锁上的被等待线程可以被同一个锁上的notify唤醒,不可以对不同锁中的线程进行唤醒。简言之,等待和唤醒必须是同一个锁。

示例:(生产者消费者)

class Resource {
       private String name;
       private int count = 1;
       private boolean flag = false;
       //t1 t2
       public synchronized void set(String name) {
              while(flag)
                     try{
                            this.wait();
                     }catch (Exception e) {
                     }//t1(放弃资格) t2(获取资格)
              this.name= name + "--" + count++;
              System.out.println(Thread.currentThread().getName()+ "...生产者.."+this.name);
              flag= true;
              this.notifyAll();
       }
       //t3 t4
       public synchronized void out() {
              while(!flag)
                     try{
                            wait();
                     }catch (Exception e) {
                     }//t3(放弃资格) t4(放弃资格)
              System.out.println(Thread.currentThread().getName()+ "...消费者........."+this.name);
              flag= false;
              this.notifyAll();
       }
}

class Producer implements Runnable {
       private Resource res;
       Producer(Resourceres) {
              this.res= res;
       }
       public void run() {
              while(true) {
                     res.set("+商品+");
              }
       }
}

class Consumer implements Runnable {
       private Resource res;
       Consumer(Resourceres) {
              this.res= res;
       }
       public void run() {
              while(true) {
                     res.out();
              }
       }
}

class ProCusDemo {
       public static void main(String[] args) {
              Resource r = new Resource();
              Producer pro = new Producer(r);
              Consumer con = new Consumer(r);
              Thread t1 = new Thread(pro);
              Thread t2 = new Thread(pro);
              Thread t3 = new Thread(con);
              Thread t4 = new Thread(con);
              t1.start();
              t2.start();
              t3.start();
              t4.start();
       }
}

运行结果:

……

Thread-0...生产者..+商品+--5579

Thread-3...消费者.........+商品+--5579

Thread-1...生产者..+商品+--5580

Thread-2...消费者.........+商品+--5580

Thread-0...生产者..+商品+--5581

Thread-3...消费者.........+商品+--5581

Thread-1...生产者..+商品+--5582

Thread-2...消费者.........+商品+--5582

Thread-0...生产者..+商品+--5583

Thread-3...消费者.........+商品+--5583

……

总结:

对于多个生产者和消费者为什么要定义while循环标记呢?因为要让被唤醒的线程再一次判断标记。

为什么要定义notifAll?因为需要唤醒对方线程,只有notify的话,很容易出现只唤醒本线程的情况,导致程序中的所有线程都等待。

★JDK1.5 中提供了多线程升级解决方案。

       将同步Synchronized替换成现实Lock操作。

       将Object中的wait,notify notifyAll,替换了Condition对象。

       该对象可以Lock锁 进行获取。

       该示例中,实现了本方只唤醒对方操作。

       Lock:替代了Synchronized

              lock

              unlock

              newCondition()

       Condition:替代了Object中的wait、notify、notifyAll

              await();

              signal();

              signalAll();

代码如下:

class Resource {
       private String name;
       private int count = 1;
       private boolean flag = false;
       //t1 t2
       private Lock lock = new ReentrantLock();
       private Condition condition_pro = lock.newCondition();
       private Condition condition_con = lock.newCondition();
       public void set(String name) throws InterruptedException {
              lock.lock();
              try {
                     while (flag)
                            condition_pro.await();//t1,t2
                     this.name = name +"--" + count++;
                     System.out.println(Thread.currentThread().getName()+ "...生产者.."+ this.name);
                     flag = true;
                     condition_con.signal();
              } finally {
                     lock.unlock();// 释放锁的动作一定要执行。
              }
       }
       //t3 t4
       public void out() throws InterruptedException {
              lock.lock();
              try{
                     while(!flag)
                            condition_con.await();
                     System.out.println(Thread.currentThread().getName()+"...消费者........."+ this.name);
                     flag= false;
                     condition_pro.signal();
              }finally {
                     lock.unlock();
              }
       }
}

class Producer implements Runnable {
       private Resource res;
       Producer(Resourceres) {
              this.res= res;
       }
       public void run() {
              while(true) {
                     try {
                            res.set("+商品+");
                     }catch (InterruptedException e) {
                     }
              }
       }
}

class Consumer implements Runnable {
       private Resource res;
       Consumer(Resourceres) {
              this.res= res;
       }
       public void run() {
              while(true) {
                     try{
                            res.out();
                     }catch (InterruptedException e) {
                     }
             }
       }
}

//主函数调用省略(与上面一致),运行效果一样

7.停止线程、守护线程

       ·定义循环结束标记

              因为线程运行代码一般都是循环,只要控制了循环即可,就是让run方法结束(线 程结束)

       ·使用interrupt(中断)方法

              该方法是结束线程的冻结状态,使线程回到运行状态中来

stop方法已经过时,那该如何停止线程呢?——只有一种方法——run方法结束

如在run方法中设置一个flag标记。

特殊情况:

当线程处于冻结状态,就不会读取到标记,那么线程就不会结束。

当没有指定的方式让冻结的线程恢复到运行状态时,这时需要对冻结进行清除,强制让线程恢复到运行状态中来,这样就可以操作标记让线程结束。

Thread类提供该方法interrupt()

守护线程:

       当正在运行的线程都是守护线程是,java虚拟机会退出,该方法必须在线程启动前调用

示例:

class StopThread implements Runnable {
       private boolean flag = true;
       public void run() {
              while(flag) {
                     System.out.println(Thread.currentThread().getName()+ "...run");
              }
       }
       public void changFlag() {
              flag= false;
       }
}

classStopThread Demo {
       public staticvoid main(String[] args) {
              StopThread st = new StopThread();
              Thread t1 = new Thread(st);
              Thread t2 = new Thread(st);
              //将t1,t2设为守护线程
              t1.setDaemon(true);
              t2.setDaemon(true);
              t1.start();
              t2.start();
              int num = 0;
              while (true) {
                     if (num++ == 10){
                            //清除冻结状态
                            t1.interrupt();
                            t2.interrupt();
                            //改变循环标记
                            st.changFlag();
                            break;
                     }
                     System.out.println(Thread.currentThread().getName()+ "..." + num);
              }
              System.out.println("over");
       }
}

运行结果:

Thread-0...run

Thread-1...run

Thread-1...run

Thread-1...run

main...1

main...2

main...3

main...4

main...5

main...6

main...7

main...8

main...9

main...10

over

8.join()方法

当A线程执行到了B线程的join方法时,A就会等待,当B线程都执行完后,A才会执行。

join可以用来临时加入线程执行。

示例:

class JoinTest implements Runnable {
       public void run() {
              for(int x = 1; x <= 10; x++) {
                     System.out.println(Thread.currentThread().getName()+"..."+ x);
              }
       }
}

class ThreadDemo {
       public static void main(String[] args) throws Exception {
              JoinTest jt=new JoinTest();
              Thread a=new Thread(jt);
              Thread b=new Thread(jt);
              a.start();
              b.start();
              a.join();
              for(int x=1;x<=10;x++){
                     System.out.println(Thread.currentThread().getName()+"..."+x);
              }
       }
}

运行结果:

Thread-1...1

Thread-1...2

Thread-1...3

Thread-1...4

Thread-0...1

Thread-0...2

Thread-0...3

Thread-0...4

Thread-0...5

Thread-0...6

Thread-0...7

Thread-0...8

Thread-0...9

Thread-0...10

main...1

main...2

main...3

main...4

main...5

main...6

main...7

main...8

main...9

main...10

Thread-1...5

Thread-1...6

Thread-1...7

Thread-1...8

Thread-1...9

Thread-1...10

总结:

问:什么时候该用多线程?

答:当某些代码需要同时被运行时,就用单独的线程进行封装

示例:

class ThreadTest{
       public static void main(Stirng[] args){
              //第一条线程
              newThread(){
                     publicvoid run(){
                            for(int  x=0;x<10;x++){
                                   System.out.println(Thread.currentThread().toString()+"…"+x);
                            }
                     }
              }.start();

       //另外一条线程
       Runnabler=new Runnable(){
              publicvoid run(){
                     for(int  x=0;x<10;x++){
                            System.out.println(Thread.currentThread().toString()+"…"+x);
                     }
              }
       };
       newThread(r).start();
       }
}

附注:

setPriority(int num)——设置线程组的最高优先级(默认为5)

toString()——返回此线程组的字符串表示形式

yield()——暂停当前正在执行的线程对象,并执行其他线程。

 

练习:(代码分析)

代码如下:

class MyThread extends Thread{
       public void run(){
              try{
                     Thread.currentThread().sleep(3000);
              }catch (InterruptedException e) {
              }
              System.out.println("MyThreadrunning");
       }
}

public class ThreadTest{
       public static void main(String argv[]) {
              MyThread t = new MyThread();
              t.run();
              t.start();
              System.out.println("ThreadTest");
         }
}

代码分析过程:

MyThread t = newMyThread();创建了一个线程。

t.run();调用MyThread对象的run方法,这里只有一个线程在运行就是主线程,当主线程执行到了run方法中的sleep(3000)时,这时主线程处于冻结状态,程序没有任何执行,过了3秒后,主线程打印了 MyThread running。run方法执行结束。

t.start();开启了t线程,有两种情况:

◆主线程在只执行了t.start()后,还具有执行权,继续往下执行,打印了Thread Test主线程结束,t线程获取执行权,调用自己的run方法,然后执行sleep(3000),冻结3秒,3秒后打印MyThreadrunning,t线程结束,整个程序结束。

◆主线程执行到t.start();开启了t线程,t线程就直接获取了cpu的执行权,就调用自己的run方法,指定到sleep(3000),t线程冻结3秒,这时t线程就释放了执行权,主线程开始执行打印了Thread Test,主线程结束,等到3秒后,t线程打印MyThread running,然后t线程结束,程序结束。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值