常用方法
-
start() 啓動線程並執行run()方法
-
run() 線程任務封裝在run()中
-
currentThread() 靜態的獲取當前線程對象的引用
-
getName() 獲取線程的名字
用法演示:Thread.currentThread().getName(); -
setName() 改變當前線程的名字
用法演示:Thread.currentThread().setName(“取個名字吧”); -
sleep(long 100) 讓正在執行的線程睡眠100毫秒
-
getPriority() 返回當前線程的優先級
-
setPriority(int newPriority) 設置線程優先級
設置級別:MAX(值10) NORM(值5) MIN(值0)
用法演示:Thread.currentThread().setPriority(Thread.MAX_PRIORITY); -
jion() 主要作用是同步,讓並行執行變成順序執行
-
interrupt() 線程中斷方法
-
yield() 靜態的 當前線程釋放當前cpu的執行權,效果不明顯,可能被線程調度
線程狀態
線程案例(賣票)
問題描述:火車站有三個窗口,一共買100張票,用多線程模擬一下窗口買票過程。
問題分析:
- 三個窗口要開三個線程
- 共同買一百張票,所以票要放在一個區域(例如static靜態方法區),讓着三個線程共同調用。
//第一種方法:繼承
package com.ticket;
public class Ticket1 {
public static void main(String[] args)
{
Window w1=new Window();
Window w2=new Window();
Window w3=new Window();
w1.setName("窗口1");
w2.setName("窗口2");
w3.setName("窗口3");
w1.start();
w2.start();
w3.start();
}
}
class Window extends Thread{
static int Tickets=100; //靜態方法區的100張票
@Override
public void run() {
while(true)
{
//如果票沒買完就一直執行
if(Tickets>0)
{
System.out.println(Thread.currentThread().getName()+"賣票,票號是:"+Tickets);
Tickets--;
}
else
{
break;
}
}
}
}
執行結果爲(截取一部分):
//第二種方式:接口
package com.ticket;
public class Ticket1 {
public static void main(String[] args)
{
Window w=new Window(); //票是共享數據
Thread t1=new Thread(w);
Thread t2=new Thread(w);
Thread t3=new Thread(w);
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
class Window implements Runnable{
private int Tickets=100; //靜態方法區的100張票
@Override
public void run() {
while(true)
{
//如果票沒買完就一直執行
if(Tickets>0)
{
System.out.println(Thread.currentThread().getName()+"賣票,票號是:"+Tickets);
Tickets--;
}
else
{
break;
}
}
}
}
執行結果(截取一部分)
線程同步問題
同步:指進程必須按照順序依次對資源進行訪問
異步:指進程之間沒有相互約束
線程同步的實現,在需要限制線程進入的地方加synchronized(對象)
例如:
//利用同步代碼塊
package com.ticket;
public class Ticket1 {
public static void main(String[] args)
{
Window w=new Window(); //票是共享數據
Thread t1=new Thread(w);
Thread t2=new Thread(w);
Thread t3=new Thread(w);
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
class Window implements Runnable{
private int Tickets=100; //靜態方法區的100張票
@Override
public void run() {
while(true)
{
//同步代碼塊
synchronized(this) //this指的是Window定義的對象
{
if(Tickets>0)
{
System.out.println(Thread.currentThread().getName()+"賣票,票號是:"+Tickets);
Tickets--;
}
else {
break;
}
}
}
}
}
//利用同步方法
package com.ticket;
public class Ticket1 {
public static void main(String[] args)
{
Window w=new Window(); //票是共享數據
Thread t1=new Thread(w);
Thread t2=new Thread(w);
Thread t3=new Thread(w);
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
class Window implements Runnable{
private int Tickets=100; //靜態方法區的100張票
@Override
public void run() {
while(true)
{
show();
}
}
//利用同步方法
public synchronized void show(){
if(Tickets>0)
{
System.out.println(Thread.currentThread().getName()+"賣票,票號是:"+Tickets);
Tickets--;
}
}
}