package com.thread;
/**
* 创建一个子线程输出从1~100的自然数
* 创建多线程的第一种方式,继承Thread类
* getName获取当前线程的名称
* setName设置当前线程的名称
* start启动子线程
* yield当前线程会释放cpu资源,如果没有其他线程占用那么该线程还会继续执行,如果有其他线程那么可能会被其他线程抢占
* join在A线程中调用B线程的该方法,表示:当A方法执行到该方法时,执行B方法,等待B方法执行完成之后,再继续执行
* isAlive判断当前线程是否还存活
* sleep(long L):显示的让当前线程睡眠L毫秒
* 线程通信,wait notify notifyAll
*
* 设置线程的优先级
* getPriority()获取当前线程的优先级
* setPriority()设置当前线程的优先级,设置线程的优先级并不会让该线程执行完成之后再执行另一个线程,只能让该线程抢到cpu资源的概率变大,一般默认优先级为5
*
* @author Administrator
*
*/
public class TestThread1 {
public static void main(String[] args) throws InterruptedException {
// Thread.currentThread().setName("主线程");
// SubThread1 subThread1 = new SubThread1();
// subThread1.setName("子线程");
// subThread1.setPriority(Thread.MAX_PRIORITY);//设置子线程的优先级为最大:10
// subThread1.start();
// for(int i = 1; i <= 100; i++){
// System.out.println(Thread.currentThread().getName()+":"+Thread.currentThread().getPriority()+":"+i);
// if( i == 50){
// subThread1.yield();//当主线程执行到50的时候释放cpu资源
// }
// if( i == 20){
// try {
// subThread1.join(); //当主线程执行到20的时候让子线程加入进来
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// }
//调用不同的线程打印偶数和奇数
OddTest odd = new OddTest();
odd.setName("打印奇数");
odd.start();
EvenTest even = new EvenTest();
even.setName("打印偶数");
even.start();
}
}
class SubThread1 extends Thread{
//重写run 方法
@Override
public void run() {
for(int i = 1; i <= 100; i++){
// try {
// Thread.sleep(1000); //每次睡眠1秒
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
System.out.println(Thread.currentThread().getName()+":"+Thread.currentThread().getPriority()+":"+i);
}
}
}
/**
* 打印奇数
* @author Administrator
*
*/
class OddTest extends Thread{
@Override
public void run() {
for(int i = 0; i < 100; i++){
if( i % 2 != 0){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
}
/**
* 打印偶数
* @author Administrator
*
*/
class EvenTest extends Thread{
@Override
public void run() {
for(int i = 0; i < 100; i++){
if( i % 2 == 0){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
}