多线程学习笔记二-Runnable

不共享变量

共创建了3个线程,每个线程都有各自的count变量,自己减少自己变量的值。变量不共享

public class MyThread extends Thread{
     
  // count用static修饰,此时就是共享变量,static变量只会实例化一次
  private int count = 5;

  public MyThread(String name) {
     
    super(name);
    this.setName(name);
  }

  @Override
  public void run() {
     
    while (count > 0) {
     
      count -- ;
      System.out.println(Thread.currentThread().getName()+"计算"+count);
    }
  }

  public static void main(String[] args) {
     
    Thread a = new MyThread("A");
    Thread b = new MyThread("B");
    Thread c = new MyThread("C");
    a.start();
    b.start();
    c.start();
  }
}

共享变量

public class MyRunnable implements Runnable{
     
  private int count = 5;

  public void run() {
     
    while (count > 0) {
     
      count -- ;
      System.out.println(Thread.currentThread().getName()+"计算"+count);
    }
  }

  public static void main(String[] args) {
     
  	// 仅仅实现了一次MyRunnable
    Runnable runnable = new MyRunnable();
    Thread a = new Thread(runnable, "A");
    Thread b = new Thread(runnable, "B");
    Thread c = new Thread(runnable, "C");
    a.start();
    b.start();
    c.start();
  }
}

总结:runnable接口的作用就是将线程与业务逻辑单元进行分离

你可能感兴趣的:(多线程,java)