java高薪之路__006_多线程

时间:2023-03-09 17:07:17
java高薪之路__006_多线程

线程的创建有两种方式

 package learn.JavaBasics.Class;

 public class ThreadDemo extends Thread {
     private static int count = 1;

     public void run() {
         System.out.println("Thread: "+count+" has started");
         ++count;
     }

     /**
      * @param args
      */
     public static void main(String[] args) {
         // TODO Auto-generated method stub
         ThreadDemo t1 = new ThreadDemo();
         ThreadDemo t2 = new ThreadDemo();
         ThreadDemo t3 = new ThreadDemo();

         new Thread(new Runnable() {

             @Override
             public void run() {
                 // TODO Auto-generated method stub
                 System.out.println("Runnable Thread has started");
             }

         }).start();

         t1.start();
         t2.start();
         t3.start();
     }
 }

线程同步

由于一个线程在操作共享数据时,在未执行完毕的情况下,另外的线程也参与进来,导致共享数据存在了安全问题解决方式:1. 同步代码块    synchronized(同步监视器) {      //操作共享数据的代码    }    同步监视器, 由任何一个类的对象来充当,哪个线程获得了监视器,哪个线程才可操作共享数据,俗称:锁    所有线程必须同用一个同步监视器, 即这个类的对象只能有一个(接口的形式使用this大体无碍,继承的方式可能会存在多个对象,慎用this)2. 同步方法    public synchronized void show() {          //操作共享数据的代码    }    此时的同步监视器是当前对象(this), 要注意当前对象是否有多个

线程通信

 package learn.JavaBasics.Class;

 class PrintNum implements Runnable{
     private int num = 1;

     @Override
     public void run() {
         // TODO Auto-generated method stub
         while(num <= 100) {
             synchronized (this) {
                 notify(); //唤醒一个顶部的wait的线程
                 try {
                     Thread.currentThread().sleep(10);
                 } catch (InterruptedException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                 }
                 System.out.println(Thread.currentThread().getName() + ":" + num);
                 ++num;

                 try {
                     wait();//把本线程wait掉
                 } catch (InterruptedException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                 }
             }
         }
     }
 }

 public class TestCommunication {
     /**
      * 交替打印1到100的数值
      */
     public static void main(String[] args) {
         // TODO Auto-generated method stub
         PrintNum p = new PrintNum();

         Thread t1 = new Thread(p);
         Thread t2 = new Thread(p);

         t1.setName("A");
         t2.setName("B");

         t1.start();
         t2.start();
     }
 }

线程死锁