-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方法 子線程執(zhí)行的方法寫在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 + "個");//獲取當前線程
}
}
}
}
}
運行結果:小明小李交替出現(xiàn)
線程的方法:yield
public class Text02 {
public static void main(String[] args) {
}
}
class Runnable1 implements Runnable{
@Override
public void run() {
Thread.yield();//把執(zhí)行的機會讓給自己或者其他
System.out.println(Thread.currentThread().getName());
}
}
線程函數(shù)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所在的線程 運行的所需數(shù)據(jù)必須等thread2線程執(zhí)行完畢
class Thread2 extends Thread{
@Override
public void run() {
System.out.println("線程2");
}
}
運行結果:
開始
線程2
結束
public class Text04 {
public static void main(String[] args) {
//優(yōu)先級別比較高的 獲取CPU執(zhí)行的概率比較大
Thread3 thread3 = new Thread3();
thread3.setPriority(9);//設置優(yōu)先級
thread3.getPriority();//獲取優(yōu)先級
//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("執(zhí)行一");
}
}
}
class Thread4 extends Thread{
@Override
public void run() {
for (int i = 0; i <10; i++) {
System.out.println("執(zhí)行二");
}
}
}
運行結果:
先執(zhí)行完線程一,然后執(zhí)行線程二;