java-线程

线程

1、三种创建方法

image

  • 继承Thread
public class MyThread extends Thread {
  public MyThread() {}

  public MyThread(String name) {
    super(name);
  }

  @Override
  public void run() {
    for (int i = 0; i < 100; i++) {
      System.out.println(getName() + ":" + i);
    }
  }
}

public class TheadDemo {
  public static void main(String[] args) {
    MyThread t1 = new MyThread("线程1");
    t1.start();
    MyThread t2 = new MyThread("线程2");
    // 守护线程,t1线程结束,t2随后也会结束,不一定能执行完成
    t2.setDaemon(true);
    t2.start();
  }
}
  • 实现 Runnable 接口
public class MyThread2 implements Runnable {
 @Override
 public void run() {
   for (int i = 0; i < 100; i++) {
     System.out.println(Thread.currentThread().getName() + ":" + i);
   }
 }
}

// 调用
   MyThread2 t = new MyThread2();
   Thread t1 = new Thread(t, "线程1");
   Thread t2 = new Thread(t, "线程2");
   t1.start();
   t2.start();
  • 实现 Callable 接口 和 Future 接口方式
// 1、实现 Callable 接口
    Callable<Integer> callable =
        new Callable<>() {
          @Override
          public Integer call() throws Exception {
            int sum = 0;
            for (int i = 0; i < 101; i++) {
              sum += i;
            }
            return sum;
          }
        };
    // 2、创建任务
    FutureTask<Integer> task = new FutureTask<>(callable);
    // 3、把任务交给线程
    Thread t1 = new Thread(task);
    // 4、开启线程
    t1.start();
    // 5、获取返回值
    Integer sum = task.get();
    System.out.println(sum);

2、常见方法

image

3、同步代码块

// 模拟卖票
public class MyThread3 extends Thread {
  // 锁一定要唯一,建议用MyThread3.class 字节码文件代替
  // static final Object obj = new Object();
  static int tickets = 0;

  @Override
  public void run() {
    while (true) {
      // 同步代码块
      synchronized (MyThread3.class) {
        if (tickets < 100) {
          try {
            Thread.sleep(10);
          } catch (InterruptedException e) {
            throw new RuntimeException(e);
          }
          tickets++;
          System.out.println(Thread.currentThread().getName() + "正在卖第 " + tickets + " 张票");
        } else {
          break;
        }
      }
    }
  }
}

public class ThreadLockDemo {
  public static void main(String[] args) {
    MyThread3 t1 = new MyThread3();
    MyThread3 t2 = new MyThread3();
    MyThread3 t3 = new MyThread3();
    t1.start();
    t2.start();
    t3.start();
  }
}

posted @ 2023-02-26 18:56  his365  阅读(12)  评论(0编辑  收藏  举报