package program;
public class Methods02 {
public static void main(String[] args) {
F f = new F();
f.start();
for (int i = 0; i < 10; i++) {
System.out.println("主线程吃了" + i + "个包子");
if (i == 5){
try {
//f.join();//子线程插队完成任务
f.yield();//线程的礼让 不一定成功
System.out.println("子线程完成任务");
} catch (RuntimeException e) {
throw new RuntimeException(e);
}
}
}
}
}
class F extends Thread{
@Override
public void run() {
while (true) {
for (int i = 0; i < 10; i++) {
System.out.println("子线程吃了" + i + "包子");
try {
Thread.sleep(100);
// System.out.println(Thread.currentThread().getName() + "正在休眠");
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + "被interupt了");
}
}
break;
}
}
}
礼让结果
不一定成功
线程插队
一定成功
练习
题目描述
1.主线程每隔1s,输出hi,一共10次
2.当输出到hi 5时,启动一个子线程(要求实现Runnable),每隔1s输出hello,等该线程输出10次hello后,退出
3.主线程继续输出hi,直到主线程退出.
4.完成代码其实线程插队…
代码
package program;
public class Metgods03 {
public static void main(String[] args) {
G g = new G();
Thread thread = new Thread(g);
for (int i = 0; i < 10; i++) {
System.out.println("hi");
if (i == 5){
try {
thread.start();
thread.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
class G implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("hello");
try {
Thread.sleep(1000);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}