-sleep:睡眠
public class Text01 {
public static void main(String[] args) throws InterruptedException {
// System.out.println("开始");
// Thread.sleep(2000);//线程谁睡俩秒
// System.out.print("结束");
Thread1 thread1 = new Thread1();
Thread xiaoming = new Thread(thread1,"小明");
xiaoming.start();
Thread xiaoli = new Thread(thread1,"小李");
xiaoli.start();
}
}
//俩个人吃苹果 俩秒吃一个 一人一个 100
class Thread1 implements Runnable{
int apple = 100; //共享的变量
//重写的run方法 子线程执行的方法写在run里面
public void run() {
while (true) {
synchronized (this) {
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
if (apple >0) {
apple--;
//Thread.currentThread()获取当前线程 getName获取当前的名字
System.out.println(Thread.currentThread().getName() + "吃了苹果,剩下" + apple + "个");//获取当前线程
}
}
}
}
}
运行结果:小明小李交替出现
线程的方法:yield
public class Text02 {
public static void main(String[] args) {
}
}
class Runnable1 implements Runnable{
@Override
public void run() {
Thread.yield();//把执行的机会让给自己或者其他
System.out.println(Thread.currentThread().getName());
}
}
线程函数join():
public class Text03 {
public static void main(String[] args) {
Thread2 thread2 = new Thread2();
System.out.println("开始");
thread2.start();
try {
thread2.join(); //加入
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("结束 ");
}
}
//如果main所在的线程 运行的所需数据必须等thread2线程执行完毕
class Thread2 extends Thread{
@Override
public void run() {
System.out.println("线程2");
}
}
运行结果:
开始
线程2
结束
public class Text04 {
public static void main(String[] args) {
//优先级别比较高的 获取CPU执行的概率比较大
Thread3 thread3 = new Thread3();
thread3.setPriority(9);//设置优先级
thread3.getPriority();//获取优先级
//thread3.setName("设置名字");
thread3.isAlive();//判断是否存活
thread3.start();
Thread4 thread4 = new Thread4();
thread4.setPriority(1);
thread4.start();
}
}
class Thread3 extends Thread{
@Override
public void run() {
for (int i = 0; i <10; i++) {
System.out.println("执行一");
}
}
}
class Thread4 extends Thread{
@Override
public void run() {
for (int i = 0; i <10; i++) {
System.out.println("执行二");
}
}
}
运行结果:
先执行完线程一,然后执行线程二;
网友评论