线程的强制执行
当满足某些条件时,某一个线程对象可以将资源一直独占,一直到线程执行结束
正常执行
public class TestThread {
public static void main(String[] args) throws Exception {
Thread thread = new Thread(() -> {
for (int x = 0; x < 100; x++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "执行" + " x = " + x);
}
}, "线程");
thread.start();
for (int x = 0; x < 100; x++) {
Thread.sleep(100);
System.out.println("main线程执行 " + "num = " + x);
}
}
}
结果如下
强制执行(在强制执行时一定要获取强制执行线程对象之后才可以调用join()方法
强制执行方法:public final void join() throws InterruptedException
public class TestThread {
public static void main(String[] args) throws Exception {
Thread mainThread = new Thread().currentThread(); //主线程
Thread thread = new Thread(() -> {
for (int x = 0; x < 100; x++) {
if(x == 3) {
try {
mainThread.join(); //主线程执行
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "执行" + " x = " + x);
}
}, "线程");
thread.start(); //子线程执行
for (int x = 0; x < 100; x++) {
Thread.sleep(100);
System.out.println("main线程执行 " + "num = " + x);
}
}
}
结果如下
线程的礼让
线程的礼让是先将资源让出去让别的线程先执行,可以使用Thread中提供的方法,礼让执行的时候每调用一次yield()方法只会礼让一次当前资源
礼让方法:public static void yield()
礼让操作
public class TestThread {
public static void main(String[] args) throws Exception {
Thread thread = new Thread(() -> {
for (int x = 0; x < 100; x++) {
if(x % 3 == 0) {
Thread.yield();
System.out.println("线程礼让执行");
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "执行" + " x = " + x);
}
}, "线程");
thread.start();
for (int x = 0; x < 100; x++) {
Thread.sleep(100);
System.out.println("main线程执行 " + "num = " + x);
}
}
}
结果如下(线程礼让后main线程执行)