/** * 线程状态 * 可运行:具备执行资格,但是还没有被cpu青睐 * 运行:正在被cpu青睐 * 阻塞:sleep,即使cpu青睐也无法执行,和死亡不一样,它阻塞完毕就活过来 * 死亡:run结束或者调用stop方法 */
public class StudySale { public static void main(String[] args) { // 当多个并发线程访问同一个对象(syncThread)中的synchronized代码块时,会锁定当前的对象,// 在同一时刻只能有一个线程得到执行,其他线程受阻塞,必须等待当前线程执行完这个代码块以后释放该对象锁,才能执行其他线程并锁定其中一个对象。
// java当中每一个对象身上都持有一个锁,遇到synchronized(this)就会给this对象身上的锁上锁,这样在锁没打开之前,别的线程永远进不来。 //当同步代码块当中代码全部执行完毕,锁就会被打开,然后由cpu随机决定下一个进来的线程。 // 可能会出现的状况--死锁:进来之后,进来的那个线程挂在里面了。 Runnable runable = new TicketManager(); Thread thread1 = new Thread(runable); thread1.start(); Thread thread2 = new Thread(runable); thread2.start(); Thread thread3 = new Thread(runable); thread3.start(); }}
public class TicketManager implements Runnable{ private int count=20; @Override public void run() { /* * 同步方法:也是上锁和开锁的机制,默认是给this对象上锁 * 1、在run方法外建立public synchronized void **(){}, * 2、将方法写入run中。 * ps:此处直接将代码块写在run方法里面了 */ synchronized (this) { for (int i = 0; i <5; i++) {// Thread.currentThread().stop(); if(count>0){ System.out.println("数"+(20-count+1)); count--; }else{ System.out.println("null"); break; } } } }}
-------------------------------------------------------------------------------------------------------------------------------------
优先级/阻塞
/** * 设置优先级和yield让步都没有太多的实际作用 * 设置睡眠和join都是发生阻塞 */
public class Mythread extends Thread{ @Override public void run() { for (int i = 0; i <6; i++) { System.out.println("子线程"+i); } }}
public class Start { public static void main(String[] args) { Thread th = new Mythread();
// 线程的优先级用1~10 表示,1的优先级最低,10的优先级最高,默认值是5。优先级表示重要程度或者紧急程度.但是能不能抢到资源也是不一定。// th.setPriority(1);
/** * 为什么调用start来间接的调用run而不是直接调用run? * start方法两个作用:1.开启一个线程 2.调用run方法 */ th.start(); for (int i = 0; i <5; i++) { try { th.join(); // 阻塞掉主线程,等自己完成后再释放 } catch (InterruptedException e) { e.printStackTrace(); }// Thread.currentThread().yield();// try {// Thread.currentThread().sleep(100);// } catch (InterruptedException e) {// e.printStackTrace();// } System.out.println("主线程"+i); } }}
转载于:https://www.cnblogs.com/sun9/p/8036166.html