线程-代码示例篇一

线程-代码示例篇

  • java线程的创建方式
  • java线程的运行方式
  • java如何创建进程
  • java线程如何销毁
  • java线程如何启动
  • java线程如何顺序执行
  • java线程如何中断
  • java线程异常处理捕获
  • java线程池异常如何捕获
  • java#ThreadMXBean

java线程的创建方式

java线程创建方式有且仅有一种!!!!

Thread t1 = new Thread(()->{},"t1");

线程池源码:

// ThreadPoolExecutor类中的execute()方法
public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        int c = ctl.get();
        if (workerCountOf(c) < corePoolSize) {
            if (addWorker(command, true))
                return;
            c = ctl.get();
        }
        if (isRunning(c) && workQueue.offer(command)) {
            int recheck = ctl.get();
            if (! isRunning(recheck) && remove(command))
                reject(command);
            else if (workerCountOf(recheck) == 0)
                addWorker(null, false);
        }
        else if (!addWorker(command, false))
            reject(command);
}   

private boolean addWorker(Runnable firstTask, boolean core) {
        // 省略其余代码
        Worker w = null;
        try {
            w = new Worker(firstTask);
            final Thread t = w.thread;
            if (t != null) {
                final ReentrantLock mainLock = this.mainLock;
                mainLock.lock();
                try {
                    int rs = runStateOf(ctl.get());

                    if (rs < SHUTDOWN ||
                        (rs == SHUTDOWN && firstTask == null)) {
                        if (t.isAlive()) // precheck that t is startable
                            throw new IllegalThreadStateException();
                        workers.add(w);
                        int s = workers.size();
                        if (s > largestPoolSize)
                            largestPoolSize = s;
                        workerAdded = true;
                    }
                } finally {
                    mainLock.unlock();
                }
                if (workerAdded) {
                    t.start();
                    workerStarted = true;
                }
            }
        } finally {
            if (! workerStarted)
                addWorkerFailed(w);
        }
        return workerStarted;
    }

 private final class Worker
        extends AbstractQueuedSynchronizer
        implements Runnable
    {
        private static final long serialVersionUID = 6138294804551838833L;

        /** Thread this worker is running in.  Null if factory fails. */
        final Thread thread;
        /** Initial task to run.  Possibly null. */
        Runnable firstTask;
        /** Per-thread task counter */
        volatile long completedTasks;

        Worker(Runnable firstTask) {
            setState(-1); // inhibit interrupts until runWorker
            this.firstTask = firstTask;
            this.thread = getThreadFactory().newThread(this);
        }

我们发现ThreadPoolExecutor#execute()里会调用addWorker()方法,添加工作线程,深入这个方法发现,Worker这个内部类,还是利用了new Thread()创建了线程。

java线程的运行方式

  1. 继承Thread类,重写run方法。

  2. 实现Runnable接口,重写run方法。

    package com.shawn.concurrent.thread;
    
    /**
     * 线程运行的demo
     * @author shawn
     */
    public class ThreadRunDemo {
    
       public static void main(String[] args) {
          Thread t1 = new MyThread("t1");
          Thread t2 = new Thread(new MyRunnableImpl(),"t2");
          t1.start();
          t2.start();
       }
    
       private static void action(){
          System.out.printf("当前线程[%s], 正在执行。。。\n",Thread.currentThread().getName());
       }
    
       private static class MyThread extends Thread{
    
          public MyThread(String name){
             super(name);
          }
    
          @Override
          public void run() {
             action();
          }
       }
    
       /**
        * 可以使用lambda表达
        */
       private static class MyRunnableImpl implements Runnable{
          @Override
          public void run() {
             action();
          }
       }
    
    
    }
    

java如何创建进程

package com.shawn.concurrent.thread;

import java.io.IOException;

/**
 * java创建进程demo
 * @author shawn
 */
public class ProcessCreatingDemo {

	public static void main(String[] args) throws IOException {
		Runtime runtime = Runtime.getRuntime();
		runtime.exec("calc");
	}

}

java线程如何销毁

public class ThreadStateDemo {

	public static void main(String[] args) {
		Thread t1 = new Thread(()->{
			System.out.printf("当前线程[%s], 正在执行...\n",Thread.currentThread().getName());
		},"t1");

		t1.start();
		System.out.printf("当前线程[%s], 是否存活[%s]\n",t1.getName(),t1.isAlive());
	}
}

在java中,执行中的线程无法被销毁,但是当Thread.isAlive()返回false时,实际底层的Thread也就被销毁了。

java线程如何启动

调用start()方法

Thread t1 = new Thread(()->{
			System.out.printf("当前线程[%s], 正在执行...\n",Thread.currentThread().getName());
		},"t1");

		t1.start();

java线程如何顺序执行

按照T1.T2.T3的顺序执行

package com.shawn.concurrent.thread;

import java.lang.Thread.State;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

/**
 * 线程执行demo
 * @author shawn
 */
public class ThreadExecutionDemo {

	public static void main(String[] args)throws Exception  {
		execByCyclicBarrier();
		TimeUnit.SECONDS.sleep(4);
		execByCountDownLatch();
		TimeUnit.SECONDS.sleep(4);
		execByWait();
		execBySleep();
		execByLoop();
		execByJoin();
	}

	private static void execByCyclicBarrier(){
		System.out.println("Thread execute by CyclicBarrier");
		CyclicBarrier latch = new CyclicBarrier(3);
		Thread t1 = new Thread(new ExecByCyclicBarrier(latch,1),"t1");
		Thread t2 = new Thread(new ExecByCyclicBarrier(latch,2),"t2");
		Thread t3 = new Thread(new ExecByCyclicBarrier(latch,3),"t3");
		t1.start();
		t2.start();
		t3.start();
	}

	private static void execByCountDownLatch(){
		System.out.println("Thread execute by CountDownLatch");
		CountDownLatch latch = new CountDownLatch(3);
		Thread t1 = new Thread(new ExecByCountDownLatch(latch,1),"t1");
		Thread t2 = new Thread(new ExecByCountDownLatch(latch,2),"t2");
		Thread t3 = new Thread(new ExecByCountDownLatch(latch,3),"t3");
		t1.start();
		t2.start();
		t3.start();
	}

	private static void execByWait(){
		System.out.println("Thread execute by wait");
		Thread t1 = new Thread(ThreadExecutionDemo::action,"t1");
		Thread t2 = new Thread(ThreadExecutionDemo::action,"t2");
		Thread t3 = new Thread(ThreadExecutionDemo::action,"t3");
		execStartAndWait(t1);
		execStartAndWait(t2);
		execStartAndWait(t3);
	}

	private static void execStartAndWait(Thread thread){
		if(State.NEW.equals(thread.getState())){
			thread.start();
		}

		while (thread.isAlive()){
			synchronized (thread){
				try {
					thread.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private static void execBySleep() throws InterruptedException {
		System.out.println("Thread execute by Sleep");
		Thread t1 = new Thread(ThreadExecutionDemo::action,"t1");
		Thread t2 = new Thread(ThreadExecutionDemo::action,"t2");
		Thread t3 = new Thread(ThreadExecutionDemo::action,"t3");
		t1.start();
		TimeUnit.SECONDS.sleep(1);
		t2.start();
		TimeUnit.SECONDS.sleep(1);
		t3.start();
		TimeUnit.SECONDS.sleep(1);
	}

	private static void execByLoop(){
		System.out.println("Thread execute by loop lock");
		Thread t1 = new Thread(ThreadExecutionDemo::action,"t1");
		Thread t2 = new Thread(ThreadExecutionDemo::action,"t2");
		Thread t3 = new Thread(ThreadExecutionDemo::action,"t3");
		t1.start();
		// 自旋
		while (t1.isAlive()){}
		t2.start();
		while (t2.isAlive()){}
		t3.start();
		while (t3.isAlive()){}
	}

	private static void execByJoin() throws InterruptedException {
		System.out.println("Thread execute by join method");
		Thread t1 = new Thread(ThreadExecutionDemo::action,"t1");
		Thread t2 = new Thread(ThreadExecutionDemo::action,"t2");
		Thread t3 = new Thread(ThreadExecutionDemo::action,"t3");
		t1.start();
		t1.join();
		t2.start();
		t2.join();
		t3.start();
		t3.join();
	}

	private static void action(){
		System.out.printf("当前线程[%s], 正在执行。。。\n",Thread.currentThread().getName());
	}

	private static class ExecByCountDownLatch implements Runnable{

		private CountDownLatch latch;

		private int delay;

		public ExecByCountDownLatch(CountDownLatch latch, int delay){
			this.latch = latch;
			this.delay = delay;
		}

		@Override
		public void run() {
			try {
				TimeUnit.SECONDS.sleep(delay);
				action();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}finally {
				latch.countDown();
			}
		}
	}

	private static class ExecByCyclicBarrier implements Runnable{

		private CyclicBarrier barrier;

		private int delay;

		public ExecByCyclicBarrier(CyclicBarrier barrier, int delay){
			this.barrier = barrier;
			this.delay = delay;
		}

		@Override
		public void run() {
			try {
				TimeUnit.SECONDS.sleep(delay);
				action();
				barrier.await();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}

java线程如何中断

/**
 * 停止线程DEMO
 *
 * @author shawn
 */
public class ThreadStopDemo {

   public static void main(String[] args) throws Exception{
      stopByInterrupt();
      stopByFlag();
   }

   private static void stopByInterrupt() throws InterruptedException{
      System.out.println("stop by Interrupt");
      Thread t = new Thread(()->{
         if(!Thread.currentThread().isInterrupted()){
            action();
         }
      },"t2");
      t.start();
      t.interrupt();
      t.join();
   }

   private static void stopByFlag() throws InterruptedException {
      System.out.println("stop by flag");
      Action action = new Action();
      Thread t = new Thread(action,"t1");
      t.start();
      action.cancel();
      t.join();
   }

   private static class Action implements Runnable{

      private volatile boolean stopped = false;

      @Override
      public void run() {
         if(!stopped){
            action();
         }
      }

      private void cancel(){
         stopped = true;
      }
   }
   
   private static void action(){
      System.out.printf("当前线程[%s], 正在执行。。。\n",Thread.currentThread().getName());
   }

}

java线程异常处理捕获

public class ThreadExceptionDemo {
	public static void main(String[] args) throws InterruptedException {
		Thread.setDefaultUncaughtExceptionHandler((thread,throwable)->{
			System.out.printf("当前线程[%s],遇到了异常,详细信息:[%s]\n",thread.getName(),throwable.getMessage());
		});
		Thread t1 = new Thread(()->{
			throw new RuntimeException("thread exception!");
		},"t1");
		t1.start();
		t1.join();
		System.out.printf("当前线程[%s],是否存活:[%s]\n",t1.getName(), t1.isAlive());
	}
}

java线程池异常如何捕获

public class ThreadPoolExecutorExceptionDemo {

   public static void main(String[] args) throws Exception{
      ThreadPoolExecutor service = new ThreadPoolExecutor(
         1,1,0,TimeUnit.MILLISECONDS,new LinkedBlockingQueue<>()
      ){
         @Override
         protected void afterExecute(Runnable r, Throwable t) {
            System.out.printf("当前线程[%s],遇到了异常,详细信息:[%s]\n",Thread.currentThread().getName(),t.getMessage());
         }
      };
      service.execute(()->{
         throw new RuntimeException("thread pool exception!!");
      });
      service.awaitTermination(1, TimeUnit.SECONDS);
      service.shutdown();
   }

}

java#ThreadMXBean

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import com.sun.management.ThreadMXBean;

public class ThreadStatusDemo {

	public static void main(String[] args) {
		ThreadMXBean bean = (ThreadMXBean)ManagementFactory.getThreadMXBean();
		long[] threadIds = bean.getAllThreadIds();
		for (long id: threadIds) {
			ThreadInfo threadInfo = bean.getThreadInfo(id);
			System.out.println(threadInfo);
			long bs =  bean.getThreadAllocatedBytes(id);
			System.out.printf("当前线程[%d, %s], 分配内存:%s KB\n",id, threadInfo.getThreadName(), bs / 1000.0);
		}
	}

}

你可能感兴趣的:(java)