1.join() 优先执行这个线程
2.yield() 让出本次执行时间片
3.setDaemon(true) 线程可以变成守护线程
import java.util.concurrent.locks.ReentrantLock; public class thread { public static void main(String[] args){ MyThread myThread = new MyThread(); Thread thread = new Thread(myThread); Thread thread1 = new Thread(myThread); thread.start(); thread1.start(); } } class MyThread implements Runnable{ private int ticket = 10; @Override public void run() { for (int i=0;i<100;i++){ method(); } } ReentrantLock lock = new ReentrantLock(); private void method() { //锁 lock.lock(); try { if(ticket>0){ ticket--; try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(ticket); } } catch (Exception e) { e.printStackTrace(); }finally { //解锁 lock.unlock(); } } }
-------------------------------------------------------------------
线程池
线程池的作用:
1.降低资源消耗
重复利用已创建的线程降低线程创建和销毁造成的消耗
2.提高响应速度
当任务到达时,不需要创建线程就可以立刻执行
3.提高线程的可管理性
对线程池可以进行统一分配,调优
Executors类
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /* * 线程池 * */ public class Demo { public static void main(String[] args) { // 创建单线程 // ExecutorService es = Executors.newSingleThreadExecutor(); // 创建固定线程 // ExecutorService es = Executors.newFixedThreadPool(2); // 创建缓存线程无大小 // ExecutorService es = Executors.newCachedThreadPool(); ScheduledExecutorService es = Executors.newScheduledThreadPool(3); // es.execute(new demo1()); // es.execute(new demo1()); // 调度,延迟3秒执行 es.schedule(new demo1(),3000, TimeUnit.MILLISECONDS); es.shutdown(); } } class demo1 implements Runnable{ @Override public void run() { for (int i=0;i<10;i++){ System.out.println(Thread.currentThread().getName()+"---"+i); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } }