Java多執行緒學習筆記(自用)

Microdust_發表於2020-11-24

Java多執行緒

Thread類中的主要方法

  1. start():開啟執行緒
  2. run():繼承重寫run()
  3. currentThread():返回當前執行緒
  4. getName():返回執行緒名
  5. setName():設定執行緒名
  6. yield():釋放cpu執行權
  7. b.join():a執行緒阻塞並等待b執行緒執行完成
  8. stop():已過時,強制結束執行緒
  9. sleep():睡眠ms
  10. isAlive():是否存活

建立方式,jdk5.0前兩種,jdk5.0後兩種

  1. 繼承Thread類
  2. 實現Runnable介面
  3. 實現Callable介面
  4. 執行緒池
1.繼承Thread的方法
/**
 * @author Microdust
 * @create 2020/11/24-19:40
 */
class MyThread extends Thread{
    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() +
                        ":" + i);
            }
        }
    }
}
public class MyThreadTest1 {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();
	t1.setName("thread1");
        t1.start();
    }

}
2.實現Runnable介面的方法
class MyThread2 implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() +
                        ":" + i);
            }
        }
    }
}
public class MyThreadTest2 {
    public static void main(String[] args) {
        MyThread2 m1 = new MyThread2();
        Thread t1 = new Thread(m1);
        t1.setName("thread1");
        t1.start();
    }

}
3.實現Callable介面的方法
class MyThread3 implements Callable {
    @Override
    public Object call() throws Exception {
        int sum = 0;
        for (int i = 0; i <= 100; i++) {
            if (i % 2 == 0) {
                sum += i;
                System.out.println(Thread.currentThread().getName() +
                        ":" + i);
            }
        }
        return sum;
    }
}
public class MyThreadTest3 {
    public static void main(String[] args) {
        FutureTask futureTask = new FutureTask(new MyThread3());//Runnable
        Thread t1 = new Thread(futureTask);
        t1.setName("thread1");
        t1.start();

        try {
            System.out.println(futureTask.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

}
4.使用執行緒池建立執行緒
class MyThread4 implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            if (i % 2 != 0) {
                System.out.println(Thread.currentThread().getName() +
                        ":" + i);
            }
        }
    }
}
class MyThread5 implements Callable{
    @Override
    public Object call() throws Exception {
        int sum = 0;
        for (int i = 0; i <= 100; i++) {
            if (i % 2 == 0) {
                sum += i;
                System.out.println(Thread.currentThread().getName() +
                        ":" + i);
            }
        }
        return sum;
    }
}
public class MyThreadTest4 {
    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(10);
//        ThreadPoolExecutor service1 = (ThreadPoolExecutor)service;
//        service1.setCorePoolSize(10);
//        service1.setKeepAliveTime(...);
        service.execute(new MyThread4());
        Future future = service.submit(new MyThread5());//返回Future類物件
        try {
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        service.shutdown();
    }


}

執行緒同步方法:

  1. Synchronized (同步程式碼塊,同步方法)同步監視器多個執行緒共用一個(共享資料時)
  2. Lock介面的實現類ReentrantLock物件的方法,lock.lock()、lock.unlock()

執行緒通訊方法:

  1. wait() 阻塞
  2. notify()/notifyAll() 喚醒

相關文章