線程相關代碼

-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í)行線程二;

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 倆個人吃蘋果( 加鎖 synchronized 和wait,notify/notifyall一起用 )pu...
    晨曦_hero閱讀 194評論 0 0
  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,765評論 18 399
  • 本文主要講了java中多線程的使用方法、線程同步、線程數(shù)據(jù)傳遞、線程狀態(tài)及相應的一些線程函數(shù)用法、概述等。 首先講...
    李欣陽閱讀 2,493評論 1 15
  • Java多線程學習 [-] 一擴展javalangThread類 二實現(xiàn)javalangRunnable接口 三T...
    影馳閱讀 2,987評論 1 18
  • 周末與一個久未見面的友人相約去烏鎮(zhèn),友人見我第一句話就是“感覺你皮膚比以前好了很多”,而這句話在之后的交談中又出現(xiàn)...
    KAKA園閱讀 180評論 0 0