线程优先级演示
package com.thread;
/**
* 线程优先级演示
* public final static int MIN_PRIORITY = 1;
* public final static int NORM_PRIORITY = 5;
* public final static int MAX_PRIORITY = 10;
* getPriority():返回当前执行线程的优先级
* setPriority(int priority):设置当前执行线程的优先级
*/
class PriorityThread extends Thread {
public void run() {
for(int i=1; i<=50; i++) {
System.out.println(getName() + " -> " + getPriority() + " -> " + i);
}
}
}
public class ThreadPriorityTest {
public static void main(String[] args) {
Thread t1 = new PriorityThread();
Thread t2 = new PriorityThread();
// 设置线程名称
t1.setName("线程1");
t2.setName("线程2");
// 设置优先级
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
}
}
Thread类中的方法介绍
package com.hpeu.thread;
/**
* Thread类中的方法介绍
* 1. getName():返回当前执行的线程名称
* 2. setName(String name):给当前执行线程指定名称
* 3. run():是线程的核心方法,所有的线程需要执行的功能代码都写在此方法中
* 4. start():让线程可以被执行;让虚拟机调用当前线程的run()方法
* 5. getId():获取当前被执行的线程的一个标识
* 6. stop():用于停止当前线程,不推荐使用,已经过时
* 7. yield():让当前线程放弃对CPU的执行权
* 8. join():当线程A中调用线程B的join()方法时,线程A就是处理阻塞状态,直到线程B执行后才能继续执行
* 9. sleep(long millis):让当前被执行的线程“睡眠”指定的毫秒数
* 10. isAlive():判断当前线程是否还存活,返回true表示存活,返回false表示已经结束
*/
class Thread1 extends Thread {
@Override
public void run() {
for(int i=2; i<100; i+=2) {
System.out.println(this.getName() + ":" + getId() + ":" + i);
// try {
// sleep(10);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// if (i % 10 == 0) {
// System.out.println("--------");
// yield();
// }
}
}
}
public class ThreadMethodTest {
public static void main(String[] args) {
Thread t1 = new Thread1();
t1.setName("线程1");
t1.start();
for(int i=1; i<100; i+=2) {
System.out.println(Thread.currentThread().getName() + ":" + i);
// if (i == 29) {
// try {
// t1.join();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
}
System.out.println(t1.isAlive());
System.out.println(Thread.currentThread().isAlive());
}
}
创建线程的第二种方式
package com.hpeu.runable;
class MyRunnable implements Runnable {
@Override
public void run() {
for(int i=2; i<100; i+=2) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
/**
* 创建线程的第二种方式:
* 实现步骤:
* 1. 编写一个自定义类,该类需要实现java.lang.Runnable接口;
* 2. 在自定义类中实现(重写)父类中的run()方法,该方法是多线程的核心方法;
* 3. 实例化自定义对象;
* 4. 创建Thread类的实例,并把自定义对象以参数的方式传Thread类;
* 5. 通过Thread类所创建的对象来调用start()方法来启动自定义线程中的run()方法;
*/
public class RunableTest {
public static void main(String[] args) {
Runnable r = new MyRunnable();
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
t1.start();
t2.start();
}
}
创建线程的两种方式
class EvenThread implements Runnable {
@Override
public void run() {
for(int i=2; i<=100; i+=2) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
/*------------------------------*/
class Thread1 extends Thread {
public Thread1(String name) {
super(name);
}
@Override
public void run() {
for(int i=1; i<=100; i+=2) {
System.out.println(getName() + ":" + i);
}
}
}