线程的开辟
1.继承方式
public class ThreadCreate {
public static void main(String[] args){
MyThread mt = new MyThread();
mt.start();
System.out.println("主线程逻辑执行结束");
}
}
class MyThread extends Thread{
@Override
public void run(){
for(int i=0;i<10;i++){
System.out.println("子线程中的逻辑"+i);
}
}
}
2.Runnable接口方式
public class ThreadCreate {
public static void main(String[] args){
Runnable r =()->{
for(int i=0;i<10;i++){
System.out.println("子线程中的逻辑"+i);
}
};
Thread t = new Thread(r);
t.start();
System.out.println("主线程逻辑执行结束");
}
}
线程的休眠
class MyThread extends Thread{
@Override
public void run(){
for(int i=0;i<10;i++){
System.out.println("子线程中的逻辑"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
线程的优先级
public class ThreadMethod {
public static void main(String[] args) {
threadPriority();
}
private static void threadPriority(){
Runnable r = ()->{
for(int i=0;i<100;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
}
};
Thread t1= new Thread(r,"Thread-1");
Thread t2= new Thread(r,"Thread-2");
t1.setPriority(10);
t2.setPriority(1);
t1.start();
t2.start();
}
}
线程的礼让
private static void threadYield(){
Runnable r = new Runnable() {
@Override
public void run() {
for(int i=0;i<10;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
if(i==3)
Thread.yield();
}
}
};
Thread t1 = new Thread(r,"Thread-1");
Thread t2 = new Thread(r,"Thread-2");
t1.start();
t2.start();
}