java多线程2——线程的基本应用

线程名称:

    在Thread类中,可以通过getName()方法取得线程名称,通过setName()方法设置线程名称
可以通过currenThread()方法取得当前线程的对象

取得当前线程名称:
T    hread.CurrentThread().getName();

java程序执行,至少启动两个线程:主线程,GC(垃圾回收机制)

判断线程是否启动:

    在java中可以通过isAlive()方法判断线程是否启动

代码实现:
class MyThread implements Runnable
{
 public void run(){ //覆写Thread类中的Run()方法
  for(int i=0;i<3;i++){
   System.out.println(Thread.currentThread().getName()
    +"运行,i="+i); //取得当前线程的名字
  }
 }
}
public class RunnableDemo01
{
 public static void main(String args[]){
  MyThread mt = new MyThread();
  Thread t = new Thread(mt,"线程");
  System.out.println("线程开始执行之前:"+ t.isAlive()); //用isAlive()方法判断线程是否启动
  t.start();
  System.out.println("线程开始执行之后:"+t.isAlive());
  for(int i=0;i<3;i++){
   System.out.println("main运行:"+i);
  }
  System.out.println("代码执行之后:"+t.isAlive());
 }

运行结果:


线程的强制启动:

    在线程操作中,可以使用join()方法让一个线程强制启动,在强制启动的线程运行期间,其他线程无法运行,直到被强制启动的线程运行完。

class MyThread implements Runnable
{
 public void run(){ //覆写Thread类中的Run()方法
  for(int i=0;i<20;i++){
   System.out.println(Thread.currentThread().getName()
    +"运行,i="+i); //取得当前线程的名字
  }
 }
}
public class RunnableDemo01
{
 public static void main(String args[]){
  MyThread mt = new MyThread();        //实例化Runnable对象
  Thread t = new Thread(mt,"线程");    //实例化Thread对象
  t.start();
  for(int i=0;i<30;i++){
   if(i>10){
    try{
     t.join();                           //线程强制执行
    }catch(InterruptedException e){}
   }
   System.out.println("Main线程运行:"+i);
  }
 }

运行结果:



线程的休眠:
    Thread.sleep()方法使线程进入休眠,时间为毫秒(ms)
线程的中断:
    当一个线程运行时,另外一个线程可以使用interrupt()方法,中断其运行状态
线程的礼让:
    当两个及以上的线程运行时,可以用yield()方法将一个线程的操作暂时让给其他线程执行
后台线程:
     在java中,只要一个程序没有执行完(一个线程在运行),则整个java的进程不会消失,所以此时可以设置一个后台线程
即使java进程结束了,此后台线程仍然会继续执行。
    可以使用setDaemon()方法实现,通过true和false进行判断是否后台运行

class MyThread implements Runnable
{
 public void run(){
  System.out,println(Thread.currentThread().getName()+"在运行");
 }
}
public class RunnableDemo01
{
 public static void main(String args[]){
  MyThread mt = new MyThread()
  Thread t = new Thread(mt,"线程");
  t.serDaemon(true); //此线程在后台运行
  t.start();
 }
}

线程的优先级:

    在java中,所有线程在运行前都会处于就绪状态,此时,线程的优先级越高,越有可能被先执行
    主方法的优先级是NORM
    线程的优先级可以通过setPriority()方法进行设置,通过getPriority()方法获取优先级

class MyThread implements Runnable
{
 public void run(){
  System.out.println(Thread.currentThread().getName()+"在运行");
 }
}
public class RunnableDemo01
{
 public static void main(String args[]){
  MyThread mt = new MyThread();
  Thread t1 = new Thread(mt,"线程A");
  Thread t2 = new Thread(mt,"线程B");
  Thread t3 = new Thread(mt,"线程C");
  //设置优先级
  t1.setPriority(Thread.MIN_PRIORITY); //优先级最低
  t2.setPriority(Thread.MAX_PRIORITY); //优先级高
  t3.setPriority(Thread.NORM_PRIORITY); //优先级一般
  t1.start();
  t2.start();
  t3.start();
  //获取优先级
  System.out.println("主方法优先级:"+Thread.currentThread().getPriority()); 
  System.out.println("MIN_PRIORITY:"+Thread.MIN_PRIORITY);
  System.out.println("NORM_PRIORITY:"+Thread.NORM_PRIORITY);
  System.out.println("MAX_PRIORITY:"+Thread.MAX_PRIORITY);

 }
}

运行结果:



线程的同步和死锁:

代码块分为四种:
    普通代码快:是直接定义在方法中的
    构造块:是直接定义在类中的,优先于构造方法执行,重复使用
    静态块:是使用static关键字声明的,有限于构造块,只使用一次
    同步代码块:使用synchronized关键字声明的代码块

同步分为两种:
    同步代码块
    同步方法
同步代码块格式:
    synchronized(同步对象){
        需要同步的代码;
}    
同步的时候必须指明同步的对象,一般情况下会将当前对象作为同步的对象,使用this表示

以卖火车票为例:
class MyThread implements Runnable
{
 private int ticket = 10; //设定总票数为10张
 public void run(){
  for(int i=0;i<100;i++){
    synchronized(this){ //对当前对象进行同步
    if(ticket>0){
     try{
      Thread.sleep(300); //加入延迟
     }catch(InterruptedException e){
      e.printStackTrace();
     }
     System.out.println("卖票:ticket = "+ticket--);
    }
   }
  }
 }
}

//设立卖票窗口

public class SyncDemo
{
 public static void  main(String args[]){
  MyThread mt = new MyThread(); //实例化Runable对象
  Thread t1 = new Thread(mt); //实例化Thread对象
  Thread t2 = new Thread(mt);
  Thread t3 = new Thread(mt);
  t1.start(); //3个窗口同时进行卖票
  t2.start();
  t3.start();
 }
}

运行结果:
   

同步方法:

同步方法定义格式:
    synchronized 方法返回值 方法名称(参数列表){}

class MyThread implements Runnable
{
 private int ticket = 10; //设定总票数为10张
 public void run(){
  for(int i=0;i<100;i++){
   this.sale(); //调用同步方法
  }
 }

 //声明同步方法
 public synchronized void sale(){
  if(ticket>0){
   try{
    Thread.sleep(300); //加入延迟
   }catch(InterruptedException e){
    e.printStackTrace();
   }
   System.out.println("卖票:ticket="+ticket--);
  }
 }
}

//设立卖票窗口

public class SyncDemo
{
 public static void  main(String args[]){
  MyThread mt = new MyThread(); //实例化Runable对象
  Thread t1 = new Thread(mt); //实例化Thread对象
  Thread t2 = new Thread(mt);
  Thread t3 = new Thread(mt);
  t1.start(); //3个窗口同时进行卖票
  t2.start();
  t3.start();
 
}

死锁:
      同步可以保证资源共享操作的正确性,但是过多的同步也会出现问题:死锁
      死锁一般情况表示两个及以上的线程处于相互等待的情况

死锁模拟代码:

class Zhangsan
{
 public void say(){
  System.out.println("张三对李四说:你给我钱,我就把奶茶给你");
 }
 public void get(){
  System.out.println("张三得到了钱");
 }
}
class Lisi
{
 public void say(){
  System.out.println("李四对张三说:你给我奶茶,我就把钱给你");
 }
 public void get(){
  System.out.println("李四得到了奶茶");
 }
}
public class SyncDemo implements Runnable
{
 private static Zhangsan zs = new Zhangsan(); //实例化static型对象
 private static Lisi ls = new Lisi();
 private boolean flag = false; //声明标识位,判断谁先说话
 public void run(){
  if(flag){
   synchronized(zs){ //同步张三
   zs.say();
   try{
    Thread.sleep(500);
   }catch(InterruptedException e){
    e.printStackTrace();
   }
   synchronized(ls){
    ls.get();
   }
  }
  }else{
   synchronized(ls){ //同步李四
   ls.say();
   try{
    Thread.sleep(500);
   }catch(InterruptedException e){
    e.printStackTrace();
   }
   synchronized(zs){
    zs.get();
   }
  }
 }
}
  public static void main(String args[]){
   SyncDemo t1 = new SyncDemo();
   SyncDemo t2 = new SyncDemo();
   t1.flag = true;
   t2.flag = false;
   Thread thA = new Thread(t1);
   Thread thB = new Thread(t2);
   thA.start();
   thB.start();
  }
}

结果:


双方都在等着对方的回答,造成都没有回应即死锁

Object类对线程的支持——等待与唤醒
Object类是所有类的父类,在此类中有下面一些方法对线程的操控有所支持:

唤醒线程有两个方法:
notify()和notifyAll()

    通常,等待的线程会按照顺序排列,使用notify()方法,唤醒第一个等待的线程
                                    使用notifyAll()方法,唤醒所有等待的线程,线程优先级越高,越有可能被先调用执行

一个线程同步的案例,生产者和消费者

class Info
{
 private String name ="令狐冲";
 private String content="华山派大师兄";
 private boolean flag = false; //定义标识位
 public synchronized void set(String name,String content){        //同步设置姓名和内容方法
  if(!flag){
   try{
    super.wait(); //加入等待
   }catch(InterruptedException e){
    e.printStackTrace();
   }
  }
  this.setName(name);
  try{
   Thread.sleep(300);                 //加入休眠操作
  }catch(InterruptedException e){
   e.printStackTrace();
  }
  this.setContent(content);
  flag = false; //操作完成,改变标志位
  super.notify(); //唤醒进程
 }
  public synchronized void get(){
  if(flag){
   try{
    super.wait();
   }catch(InterruptedException e){
    e.printStackTrace();
   }
  }
  try{
   Thread.sleep(300);
  }catch(InterruptedException e){
   e.printStackTrace();
  }
  System.out.println(this.getName()+"-->"+this.getContent());
  flag = true;
  super.notify();
 }
 public void setName(String name){
  this.name = name;
 }
 public void setContent(String content){
  this.content = content;
 }
 public String getName(){
  return this.name;
 }
 public String getContent(){
  return this.content;
 }
}
class Producer implements Runnable
{
 private Info info = null;
 public Producer(Info info){
  this.info = info;
 }
 public void run(){
  boolean flag = false;
  for(int i=0;i<50;i++){
   if(flag){
    this.info.set("令狐冲","华山派大师兄");
    flag = false;
   }else{
    this.info.set("任盈盈","黑木崖圣姑");
    flag = true;
   }
  }
 }
}
class Consumer implements Runnable //使用Runnable接口,实现多线程
{
 private Info info = null; //保存Info引用
 public Consumer(Info info){
  this.info = info;
 }
 public void run(){
  for(int i=0;i<50;i++){
   this.info.get();
  }
 }
}
public class SyncDemo01
{
 public static void main(String args[]){
  Info info = new Info(); //实例化Info对象
  Producer pro = new Producer(info); //生产者
  Consumer con = new Consumer(info); //消费者
  new Thread(pro).start();
  new Thread(con).start();
 }
}

执行结果:

生产者和消费者一一对应,内容正确,也不会重复

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值