Java多線程(一)

念你的時(shí)光比相愛長


圖片發(fā)自簡書App

繼承Thread實(shí)現(xiàn)多線程

package c1;

public class ThreadText extends Thread{

    private int count=10;
    public void run() {
        
        while(count!=0) {
            System.out.println(count+" ");
            count--;
        }
    }
    public static void main(String[] args) {
        ThreadText text=new ThreadText();
        text.start();
    }
    
}
  • 運(yùn)行結(jié)果:


    image.png

實(shí)現(xiàn)Runnable接口實(shí)現(xiàn)多線程

package c2;

import java.awt.Color;
import java.awt.Container;
import java.net.URL;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;

public class SwingAndThread extends JFrame{
    
    private int count=0;
    
    public SwingAndThread() {
        
        Container container=getContentPane();
        JLabel jl=new JLabel();
        
        URL url=SwingAndThread.class.getResource("cc.png");
        Icon icon=new ImageIcon(url);
        jl.setIcon(icon);
        
        jl.setBounds(10,10,70,80);
        
        Thread t=new Thread(new Runnable() {
            
            public void run() {
                
                while(count<=200) {
                    jl.setBounds(count, 10, 70, 80);
                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    count+=4;
                    if(count==200) {
                        count=10;
                    }
                }
            }
        });
        t.start();
        container.add(jl);
        setBounds(300,200,250,100);//橫坐標(biāo),縱坐標(biāo),長,寬
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        
    }
    public static void main(String[] args) {
        new SwingAndThread();
    }
    
}

  • 運(yùn)行結(jié)果:滾動(dòng)的圖標(biāo)
image.png

線程的生命周期

  • java線程有七種狀態(tài),出生狀態(tài),就緒狀態(tài),運(yùn)行狀態(tài),等待狀態(tài),休眠狀態(tài),阻塞狀態(tài)和死亡狀態(tài)。
  • 調(diào)用start()方法之前都處于出生狀態(tài)
  • 調(diào)用start()方法之后為就緒狀態(tài)(可執(zhí)行狀態(tài))
  • 線程得到系統(tǒng)資源后進(jìn)入運(yùn)行狀態(tài)
  • 調(diào)用wait()方法進(jìn)入等待狀態(tài)
  • 用notify()方法喚醒等待狀態(tài)的線程
    notifyAll()方法喚醒所有等待線程
  • sleep()方法進(jìn)入休眠狀態(tài)
  • 如果一個(gè)線程在運(yùn)行狀態(tài)下發(fā)出 輸入/輸出 請求,該線程進(jìn)入阻塞狀態(tài),
    線程等待 輸入/輸出 結(jié)束時(shí)的狀態(tài)為就緒狀態(tài)
  • 當(dāng)線程的run()方法執(zhí)行完畢進(jìn)入死亡狀態(tài)
image.png
  • 線程的休眠:

在窗口中畫線,并產(chǎn)生隨機(jī)顏色,運(yùn)用線程休眠進(jìn)行延時(shí)

package c3;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Window;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.WindowConstants;

public class SleepText extends JFrame{

    private Color[] color= {
            Color.BLACK,Color.BLUE,Color.GREEN,Color.RED,Color.YELLOW
    };
    
    private Random rand=new Random();
    
    private Color getC() {
        
        return color[rand.nextInt(color.length)];
        
    }
    public SleepText() {
        Thread t=new Thread(new Runnable() {

            int x=30;
            int y=50;
            public void run() {
                while(true) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        
                        e.printStackTrace();
                    }
                    Graphics graphics=getGraphics();
                    graphics.setColor(getC());
                    graphics.drawLine(x, y, 100, y++);
                    if(y>=80) {
                        y=50;
                    }
                }
            }
        });
        t.start();
    }

    public static void main(String[] args) {
        init(new SleepText(),100,100);//在靜態(tài)方法中不可以調(diào)用非靜態(tài)方法
    }

    public static void init(JFrame frame,int wdith,int height) {
        
        frame.setSize(wdith,height);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}
  • 在靜態(tài)方法中不可以調(diào)用非靜態(tài)方法

  • 線程的加入:

package c4;

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.WindowConstants;

public class JoinText extends JFrame{

    private Thread t1;
    private Thread t2;
    
    final JProgressBar progressBar1=new JProgressBar();
    final JProgressBar progressBar2=new JProgressBar();
    
    
    
    public static void main(String[] args) {
        init(new JoinText(),100,100);
    }
    
    public JoinText() {
        
        super();
        getContentPane().add(progressBar1, BorderLayout.NORTH);
        getContentPane().add(progressBar2, BorderLayout.SOUTH);
        progressBar1.setStringPainted(true);
        progressBar2.setStringPainted(true);
        t1=new Thread(new Runnable() {
            int count=0;
            public void run() {
                while(true) {
                    progressBar1.setValue(++count);
                    try {
                        Thread.sleep(50);
                        if(count==50){
                            t2.join();
                                                }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t1.start();
        t2=new Thread(new Runnable() {
            int count=0;
            public void run() {
                while(true) {
                    progressBar2.setValue(++count);
                    try {
                        Thread.sleep(50);
                        
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if(count==100) {
                        break;
                    }
                }
            }
        });
        t2.start();
    }

    public static void init(JFrame frame, int width, int height) {
        // TODO Auto-generated method stub
        frame.setSize(width,height);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

運(yùn)行結(jié)果:


1.png
2.png

  • 線程的同步(資源共享問題)

同步塊實(shí)現(xiàn):

package c5;

public class Synchronized implements Runnable{

    int num=10;
    
    public void run() {
        
        while(true) {
            synchronized ("") {//線程的同步(資源共享問題)
                
                if(num>0) {
                    try {
                        Thread.sleep(100);
                        
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(--num);
                }
            }
        }
    }
    
    public static void main(String[] args) {
        
        Synchronized sy=new Synchronized();
        
        Thread t1=new Thread(sy);
        Thread t2=new Thread(sy);
        Thread t3=new Thread(sy);
        Thread t4=new Thread(sy);
        
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

也可以這么寫,(同步方法實(shí)現(xiàn)):

public synchronized void doit() {
        
        if(num>0) {
            try {
                Thread.sleep(100);
                
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(--num);
        }
    }
    
    public void run() {
        
        while(true) {
            doit();
        }
    }

運(yùn)行結(jié)果:


image.png

總結(jié):

start();//線程處于就緒狀態(tài)(可執(zhí)行狀態(tài))
wait();//線程進(jìn)入等待(進(jìn)入就緒狀態(tài))
sleep();//線程進(jìn)入休眠(進(jìn)入就緒狀態(tài))
notify();//喚醒等待線程(進(jìn)入運(yùn)行狀態(tài))
notifyAll();//喚醒所以等待下的線程(進(jìn)入運(yùn)行狀態(tài))
join();//線程的加入
interrupt();//線程的中斷,使線程離開run()方法,同時(shí)結(jié)束線程,但會拋出異常
setPriority();//線程的優(yōu)先級,范圍10-1,數(shù)越大優(yōu)先級越高

synchronized(""){
  //線程同步機(jī)制,多個(gè)線程訪問一個(gè)資源代碼時(shí),
//將共享的資源放在這里,在一個(gè)時(shí)間內(nèi)只有一個(gè)線程執(zhí)行共享代碼了。
}
  • 線程中斷還可以在while(true){}里設(shè)置一個(gè) if 條件語句,如果成立就break;

PS:執(zhí)行代碼的時(shí)候,好幾個(gè)線程同時(shí)執(zhí)行,CPU使用率達(dá)到100%了,尤其是沒用 synchronized 訪問同一資源代碼的時(shí)候?。?!

參考資料:

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 線程概述 線程與進(jìn)程 進(jìn)程 ?每個(gè)運(yùn)行中的任務(wù)(通常是程序)就是一個(gè)進(jìn)程。當(dāng)一個(gè)程序進(jìn)入內(nèi)存運(yùn)行時(shí),即變成了一個(gè)進(jìn)...
    閩越布衣閱讀 1,101評論 1 7
  • 一、基本概念:程序 - 進(jìn)程 - 線程 程序(program):是為完成特定任務(wù)、用某種語言編寫的一組指令的集合。...
    c5fc16271aee閱讀 543評論 0 2
  • 本文主要講了java中多線程的使用方法、線程同步、線程數(shù)據(jù)傳遞、線程狀態(tài)及相應(yīng)的一些線程函數(shù)用法、概述等。 首先講...
    李欣陽閱讀 2,599評論 1 15
  • 開始按照你的確定信念行事吧。 今天的內(nèi)容是接續(xù)昨天內(nèi)容中的練習(xí)的??梢詤⒖伎匆幌碌?5天早讀的文章。你寫下來自己正...
    然媽Miya閱讀 436評論 0 0
  • 胡洋給我打電話的時(shí)候是下午兩點(diǎn),我剛吃過飯,她哭著跟我說,和徐林分手了。電話里她泣不成聲,聽不清說了什么,沒說多久...
    艾米小姐閱讀 827評論 0 1

友情鏈接更多精彩內(nèi)容