线程的优先级:
线程的优先级分为三种,分别是:
1-MIN_PRIORITY
10-MAX_PRIORITY
5-NORM_PRIORITY
如果什么都不设置默认值是5
线程的优先级可以影响线程的执行顺序,当然这里指的是有可能影响,不会一定影响。在默认状态下(比如说主线程)它的默认值是5
具体代码演示:
package com.yeqc.thread; class ThRun implements Runnable{ @Override public void run() { for(int i=0; i<5; i++){ try { Thread.sleep(1000); System.out.println(Thread.currentThread().getName()+":"+i); } catch (InterruptedException e) { e.printStackTrace(); } } } } public class ThreadDemo03 { public static void main(String[] args) { Thread t1 = new Thread(new ThRun(),"A"); Thread t2 = new Thread(new ThRun(),"B"); Thread t3 = new Thread(new ThRun(),"C"); t1.setPriority(Thread.MIN_PRIORITY); t2.setPriority(Thread.NORM_PRIORITY); t3.setPriority(Thread.MAX_PRIORITY); t1.start(); t2.start(); t3.start(); } }
运行结果:
C:0 A:0 B:0 C:1 B:1 A:1 C:2 A:2 B:2 C:3 A:3 B:3 C:4 B:4 A:4
同步与死锁:
1.同步代码块
在代码块上加上“synchronized”关键字,则此代码块就称为同步代码块
2.同步代码块格式:
sychronized(同步对象){ 需要同步的代码块; }
3.同步方法
除了代码块可以同步,方法也是可以同步的
4.方法同步格式:
sychronized void 方法名称(){}
具体代码演示:
1.同步代码块方式:
package com.yeqc.thread; class MythreadDemo implements Runnable{ private int ticket = 5; @Override public void run() { for (int i = 0; i < 10; i++) { synchronized (this) { if (ticket>0) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("车票:"+ticket--); } } } } } public class ThreadDemo04 { public static void main(String[] args) { MythreadDemo m = new MythreadDemo(); Thread t1 = new Thread(m); Thread t2 = new Thread(m); Thread t3 = new Thread(m); t1.start(); t2.start(); t3.start(); } }
运行结果:
车票:5 车票:4 车票:3 车票:2 车票:1
2.同步方法
package com.yeqc.thread; class MythreadDemo implements Runnable{ private int ticket = 5; @Override public void run() { for (int i = 0; i < 10; i++) { tell(); } } public synchronized void tell(){ if (ticket>0) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("车票:"+ticket--); } } } public class ThreadDemo04 { public static void main(String[] args) { MythreadDemo m = new MythreadDemo(); Thread t1 = new Thread(m); Thread t2 = new Thread(m); Thread t3 = new Thread(m); t1.start(); t2.start(); t3.start(); } }
运行结果:
车票:5 车票:4 车票:3 车票:2 车票:1
/**
*死锁:学生找工作(高新)
* 企业需要你有工作经验(经验)
*/
原文地址:http://11317783.blog.51cto.com/11307783/1769371