多线程
时间:2019-04-09 01:01:35
收藏:0
阅读:163
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(); } } }
原文:https://www.cnblogs.com/mm163/p/10674506.html
评论(0)