Java 多线程

2020-08-04 22:11:57 浏览数 (1)

1.方法一创建线程
代码语言:javascript复制
    /**
     * 1.创建线程类
     * 多线程需要创建多个类对象
     * 2.调用start()方法
     * @param args
     */
    
     public static void main(String[] args) {
        MyThread my = new MyThread();
        MyThread my1 = new MyThread();
        my1.start();
        my.start();
    }
2.无参与带参给线程起名
代码语言:javascript复制
  带参时需要给继承线程类写带参数的构造方法
代码语言:javascript复制
    /**
     * 如何获取线程的名称
     * public final String getName()
     * 
     * 
     */
      public static void main(String[] args) {
          //无参线程起名
//      //创建线程对象
//      MyThread my = new MyThread();
//      MyThread my1 = new MyThread();
//      //设置名称
//       my.setName("林");
//       my1.setName("我");
//      //启动线程
//      my.start();
//      my1.start();
          //带参起名
          MyThread my = new MyThread("张飞");
          MyThread my1 = new MyThread("李逵");
          my.start();
          my1.start();
}
3.设置线程的优先级
代码语言:javascript复制
 public static void main(String[] args) {
          //无参线程起名
//      //创建线程对象
        MyThread my = new MyThread();
        MyThread my1 = new MyThread();
        //设置名称
         my.setName("林");
         my1.setName("我");
         my.setPriority(1);
         my1.setPriority(10);
        //启动线程
        my.start();
        my1.start();
}
4.线程睡眠
代码语言:javascript复制
 public void run() {
            for(int i =0 ;i<100;i  ){
                System.out.println(getName() "---" i ",日期:" new Date());
                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
5.线程的加入
代码语言:javascript复制
public static void main(String[] args) throws Exception {
          //无参线程起名
//      //创建线程对象
        MyThread my = new MyThread();
        MyThread my1 = new MyThread();
        MyThread my2 = new MyThread();
        //设置名称
         my.setName("李渊");
         my1.setName("李世民");
         my2.setName("李元霸");
//       my.setPriority(1);
//       my1.setPriority(10);
        //启动线程
        my.start();
        my.join();
        my1.start();
        my2.start();
}
6.线程的礼让
代码语言:javascript复制
            public void run() {
            for(int i =0 ;i<100;i  ){
                System.out.println(getName() "---" i ",日期:" new Date());
                Thread.yield();//线程礼仪,但是不能保证
            }
7.守护线程
代码语言:javascript复制
  public static void main(String[] args) throws Exception {
          MyThread my1 = new MyThread();
          MyThread my2 = new MyThread();
          
          my1.setName("张飞");
          my2.setName("关羽");
          //守护线程在线程启动前设置
          my1.setDaemon(true);
          my2.setDaemon(true);
          my1.start();
          my2.start();
          
          Thread.currentThread().setName("刘备");
          for(int i=0;i<5;i  ){
              System.out.println(Thread.currentThread().getName() i new Date());
          }
    }
8.火车买票系统
代码语言:javascript复制
1,Thread类
public class MyThread extends Thread{
    
    private static int tackets = 100;
    @Override
    public void run() {
        while(true){
        if(tackets>0){
            System.out.println(getName() "正在销售第" (tackets--) "张票");
        }
      }
    }
}
public class SellTackets {
    
     public static void main(String[] args) {
         //
         MyThread s1 = new MyThread();
         MyThread s2 = new MyThread();
         MyThread s3 = new MyThread();
         //起名
         s1.setName("窗口1");
         s2.setName("窗口2");
         s3.setName("窗口3");
         s1.start();
         s2.start();
         s3.start();
    }

}
2.Runnable类
public class MyRunnable implements Runnable{

    private int tackets = 100;
    @Override
    public void run() {
         while(true){
            if(tackets>0){
                System.out.println(Thread.currentThread().getName() "正在销售第" (tackets--) "张票");
            }else{
                break;
            }
       }
    }
}
public class SellTackets {
      
       public static void main(String[] args) {
          MyRunnable my = new MyRunnable();
          
          Thread t1 = new Thread(my,"窗口1");
          Thread t2 = new Thread(my,"窗口2");
          Thread t3 = new Thread(my,"窗口3");
          t1.start();
          t2.start();
          t3.start();
    }

}
9.火车售票的改进
代码语言:javascript复制
public class RunnableDemo {
    
     public static void main(String[] args) {
         //创建对象
        SellTacketsRunnable str = new SellTacketsRunnable();
         Thread t1 = new Thread(str,"张晓天");
         Thread t2 = new Thread(str,"陈建冰");
         Thread t3 = new Thread(str,"冰冰");
         
         t1.start();
         t2.start();
         t3.start();
    }

}
public class SellTacketsRunnable implements Runnable{
   //定义100张火车票
    private int tackets = 100;
   //定义同一把锁
    private Object obj = new Object();
    @Override
    public void run() {
        while(true){
         synchronized (obj) {
            
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
                if(tackets>0){
                    System.out.println(Thread.currentThread().getName() "正在售出第" (tackets--) "张票");
                }else{
                    break;
                }
            }
        }
    }

}
10.使用Lock加锁与释放锁
代码语言:javascript复制
/**
     * public interface Lock获取锁
     * void unlock()释放锁
     */
    //定义票的数量
    private int tackets = 100;
    private Lock lock = new ReentrantLock();
    @Override
    public void run() {
       
        while(true){
            try{
            //加锁
            lock.lock();
            if(tackets>0){
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() "正在销售第" (tackets--) "张票");
            }
            else{
                break;
            }
            }finally{
            lock.unlock();
            }
        }
        
    }

}
11.java的等待唤醒机制,该方法在Object类中
代码语言:javascript复制
public class Student {
     
      private String name ;
      private int    age  ;
      public  boolean   flag; 
    public Student() {
        super();
    }
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
     }
import cn.bipt.thread.entity.Student;

public class consumer implements  Runnable {
    
    private Student s;
    
    public consumer(Student s){
        this.s = s;
    }
    
    public void run() {
        while(true){
            synchronized (s) {
                if(!s.flag){
                    try {
                        s.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(s.getName() "---" s.getAge());
                //修改标记
                s.flag = false;
                //唤醒线程
                s.notify();
            }
        }
    }

}
import cn.bipt.thread.entity.Student;

public class Product implements Runnable{

    private Student s;
    private int cycle = 10;
    public Product(Student s){
        this.s = s;
    }
    @Override
    public void run() {
      while(true){
          synchronized (s) {
              if(s.flag){
                  try {
                    s.wait();
                } catch (InterruptedException e) {

                    e.printStackTrace();
                }
              }
              if(cycle%2==0){
                  
                  s.setName("陈建兵");
                  s.setAge(19);
                  cycle  ;
              }else{
                  s.setName("张晓天");
                  s.setAge(20);
                  cycle  ;
              }
              //修改标记
              s.flag = true;
              //唤醒
              s.notify();
        }
      }
    }

}
public class ThreadDemo {
     public static void main(String[] args) {
        
         Student s = new Student();
         Product pro = new Product(s);
         consumer con = new consumer(s);
         
         Thread t1 = new Thread(pro);
         Thread t2 = new Thread(con);
         
         t1.start();
         t2.start();
    }
}
12.线程池
代码语言:javascript复制
public class ExecutorsDemo {
     
     public static void main(String[] args) {
        
         ExecutorService pool = Executors.newFixedThreadPool(2);
         
         pool.submit(new MyRunnable());
         pool.submit(new MyRunnable());
         
         
    }

}
13.定时器
代码语言:javascript复制
public class timerDemo {
       public static void main(String[] args) {
        //创建定时器对象
           Timer t = new Timer();
           t.schedule(new Mytask(), 3000);
    }
}
class Mytask extends TimerTask{

    @Override
    public void run() {
        
        System.out.println("beng,爆炸了");
        
    }
    
}
//每隔几秒再炸
public class timerDemo {
       public static void main(String[] args) {
        //创建定时器对象
           Timer t = new Timer();
           //三秒后爆炸,然后两秒后再炸
           t.schedule(new Mytask(), 3000,2000);
    }
}
class Mytask extends TimerTask{

    @Override
    public void run() {
        
        System.out.println("beng,爆炸了");
        
    }
    
}
多线程.jpeg多线程.jpeg

0 人点赞