package thread;
public class Test01 extends Thread{
int coun = 0;
@Override
public void run(){
// currentThread():返回当前线程
System.out.println(Thread.currentThread().getName()+"线程运行的代码");
for (int i = 0; i < 5; i++) {
coun++;
System.out.println(Thread.currentThread().getName()+"这是逻辑代码"+coun);
}
}
}
class T{
public static void main(String[] args) {
Thread t= new Test01();
Thread t1= new Test01();
Thread tt = new Thread(t);
Thread tt1 = new Thread(t1);
tt.start();
// 设置名称
tt.setName("儿子");
tt1.setName("儿子1");
System.out.println("===========================");
tt1.start();
System.out.println("=========================");
// 如果在创建线程的时候没有给名称,那么得到的就是系统默认的名称3
System.out.println(tt.getName());
System.out.println(tt1.getName());
/**
* 线程的优先级:就是哪个线程有较大概率先执行
* 优先级是用数组1-10表示,数字越大优先级越高如果没有设置就默认5
*/
// 查看线程优先级
System.out.println(tt.getPriority());
System.out.println(tt1.getPriority());
// 设置线程优先级
tt.setPriority(1);
tt1.setPriority(10);
System.out.println(tt.getPriority());
System.out.println(tt1.getPriority());
}
}
package thread;
public class Demo01 extends Thread{
int coun = 0;
@Override
public void run(){
// currentThread():返回当前线程
System.out.println(Thread.currentThread().getName()+"线程运行的代码");
for (int i = 0; i < 5; i++) {
// 线程休眠(毫秒)
try {
Thread.sleep(1000);//当前线程休眠1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
if (i%2==0) {
// 线程让步:暂停当前正在执行的线程,把机会让给优先级一样或更高的线程,如果没有就忽略该方法
Thread.yield();
}
coun++;
System.out.println(Thread.currentThread().getName()+"这是逻辑代码"+coun);
}
}
}
class B{
public static void main(String[] args) throws InterruptedException {
Thread demo01 = new Demo01();
Thread demo02= new Demo01();
Thread thread = new Thread(demo01);
Thread thread1 = new Thread(demo02);
System.out.println("111111111111111111111111");
thread.start();
thread1.start();
// 判断线程是否还活着
System.out.println(thread1.isAlive());
System.out.println("22222222222222222222222");
// 强行结束线程
thread.stop();
System.out.println("333333333333333333333");
thread.join();//相当于把run()代码插到这里面执行,等到它执行完毕才会执行其他
// 规范名称:堵塞当前的方法,先执行join方法
System.out.println("4444444444444444444444");
}
}