王照陆博客

线程优先级/* * 线程优先级,范围[1,10] * 不同优先级的线程获取执行的机会不同,优先级越高,执行机会越大 * * 对比不同优先级的线程被执行的机率 */{main(String[] args) {System.out.println(“最大优先级:” + Thread.MAX_PRIORITY);System.out.println(“最小优先级:” + Thread.MIN_PRIORITY);System.out.println(“中等优先级:” + Thread.NORM_PRIORITY);System.out.println(“主线程默认优先级:” + Thread.currentThread().getPriority());System.out.println(“***********************\n”);MyThread3 t1=new MyThread3();t1.setPriority(10);t1.start();MyThread4 t2=new MyThread4(3);t2.start();while (true) {System.out.println(Thread.currentThread().getName() + “,优先级:”+ Thread.currentThread().getPriority());}}} Thread {@Overridepublic void run() {while (true) {System.out.println(Thread.currentThread().getName() + “,,优先级:”+ getPriority());}}} Thread {public MyThread4(int priority) {setPriority(priority);}@Overridepublic void run() {while (true) {System.out.println(Thread.currentThread().getName() + “,优先级:”+ getPriority());}}}sleep()和yield()import java.text.SimpleDateFormat;import java.util.Date;/* * sleep()和yield() */{main(String[] args) {/*MyThread5 mt = new MyThread5(250);Thread thread = new Thread(mt, “first”);thread.start();*/MyThread6 mt = new MyThread6();Thread thread = new Thread(mt, “second”);thread.start();while(true){Thread.yield();System.out.println(Thread.currentThread().getName()+”****”);}}} num;public MyThread5(int num) {this.num = num;}@Overridepublic void run() {while (num > 0) {try {Thread.sleep(8000);//sleep使线程从执行状态进入休眠状态System.out.println(Thread.currentThread().getName() + “****”+ num–);} catch (InterruptedException e) {e.printStackTrace();}}}} Runnable{@Overridepublic void run() {SimpleDateFormat sdf=new SimpleDateFormat(“yyyy-MM-dd hh:mm:ss”);while(true){//yield方法使线程从执行状态进入准备就绪状态Thread.yield();System.out.println(Thread.currentThread().getName()+”,当前时间:”+sdf.format(new Date()));}}}join()方法/* * join()方法 */{main(String[] args) {MyThread7 mt = new MyThread7();Thread t1 = new Thread(mt, “first”);Thread t2 = new Thread(mt, “second”);t1.start();t2.start();//当线程二执行完以后再执行主线程try {System.out.println(“t2 is alive?”+t2.isAlive());t2.join();System.out.println(“t2 is alive?”+t2.isAlive());} catch (InterruptedException e) {e.printStackTrace();}for (int i = 1; i <= 100; i++) {System.out.println(Thread.currentThread().getName() + “****” + i);}}} Runnable {@Overridepublic void run() {for (int i = 1; i <= 100; i++) {System.out.println(Thread.currentThread().getName() + “****” + i);}}}

游手好闲会使人心智生锈

王照陆博客

相关文章:

你感兴趣的文章:

标签云: