创建一个继承于Thread的子类
重写Thread类的run()-->将此线程执行的操作声明在run()
创建Thread类的子类对象
通过此对象调用start()
? 练习
package com.yicurtain.THREAD;
//创建一个继承于Thread的子类
class MYThread extends Thread{
//重写Thread类的run()
@Override
public void run() {
for (int i = 2; i < 100; i++) {
boolean flag=true;
for (int j = 2; j <= Math.sqrt(i); j++) {
if(i%j==0){
flag=false;
break;
}
}
if (flag){
System.out.println(i);
}
}
}
}
public class ThreadTest {
public static void main(String[] args) {
//创建Thread类的子类对象
MYThread t1 = new MYThread();
//通过此对象调用start()
t1.start();
}
}
package com.yicurtain.THREAD;
/*
创建2个线程,一个线程执行100以内的奇数,一个线程执行100以内的偶数
*/
class MYThread1 extends Thread{
@Override
public void run() {
for (int i = 1; i <101 ; i++) {
if(i%2==0){
System.out.println("偶数:"+i);
}
}
}
}
class MYThread2 extends Thread{
@Override
public void run() {
for (int i = 1; i <101 ; i++) {
if(i%2 != 0){
System.out.println("奇数:"+i);
}
}
}
}
public class ThraedDemo {
public static void main(String[] args) {
MYThread1 t1 = new MYThread1();
MYThread2 t2 = new MYThread2();
t1.start();
t2.start();
}
}
MAX_PRIORITY:10
MIN _PRIORITY:1
NORM_PRIORITY:5
如何设置线程的优先级:
getPriority():获取线程的优先级
setPriority(int p):设置线程的优先级
说明:高优先级的线程要抢占低优先级线程cpu的执行权.但是只是从概率上讲,高优先级的线程高概率的情况下被执行.并不意味着只有当高优先级的线程执行完以后,低优先级的线程才执行.
原文:https://www.cnblogs.com/yicurtain/p/14894732.html