Java多线程(一)

念你的时光比相爱长


图片发自简书App

继承Thread实现多线程

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();
    }
    
}
  • 运行结果:


    image.png

实现Runnable接口实现多线程

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);//横坐标,纵坐标,长,宽
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        
    }
    public static void main(String[] args) {
        new SwingAndThread();
    }
    
}

  • 运行结果:滚动的图标
image.png

线程的生命周期

  • java线程有七种状态,出生状态,就绪状态,运行状态,等待状态,休眠状态,阻塞状态和死亡状态。
  • 调用start()方法之前都处于出生状态
  • 调用start()方法之后为就绪状态(可执行状态)
  • 线程得到系统资源后进入运行状态
  • 调用wait()方法进入等待状态
  • 用notify()方法唤醒等待状态的线程
    notifyAll()方法唤醒所有等待线程
  • sleep()方法进入休眠状态
  • 如果一个线程在运行状态下发出 输入/输出 请求,该线程进入阻塞状态,
    线程等待 输入/输出 结束时的状态为就绪状态
  • 当线程的run()方法执行完毕进入死亡状态
image.png
  • 线程的休眠:

在窗口中画线,并产生随机颜色,运用线程休眠进行延时

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);//在静态方法中不可以调用非静态方法
    }

    public static void init(JFrame frame,int wdith,int height) {
        
        frame.setSize(wdith,height);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}
  • 在静态方法中不可以调用非静态方法

  • 线程的加入:

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);
    }
}

运行结果:


1.png
2.png

  • 线程的同步(资源共享问题)

同步块实现:

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();
    }
}

也可以这么写,(同步方法实现):

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();
        }
    }

运行结果:


image.png

总结:

start();//线程处于就绪状态(可执行状态)
wait();//线程进入等待(进入就绪状态)
sleep();//线程进入休眠(进入就绪状态)
notify();//唤醒等待线程(进入运行状态)
notifyAll();//唤醒所以等待下的线程(进入运行状态)
join();//线程的加入
interrupt();//线程的中断,使线程离开run()方法,同时结束线程,但会抛出异常
setPriority();//线程的优先级,范围10-1,数越大优先级越高

synchronized(""){
  //线程同步机制,多个线程访问一个资源代码时,
//将共享的资源放在这里,在一个时间内只有一个线程执行共享代码了。
}
  • 线程中断还可以在while(true){}里设置一个 if 条件语句,如果成立就break;

PS:执行代码的时候,好几个线程同时执行,CPU使用率达到100%了,尤其是没用 synchronized 访问同一资源代码的时候!!!

参考资料:

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 线程概述 线程与进程 进程  每个运行中的任务(通常是程序)就是一个进程。当一个程序进入内存运行时,即变成了一个进...
    闽越布衣阅读 4,583评论 1 7
  • 一、基本概念:程序 - 进程 - 线程 程序(program):是为完成特定任务、用某种语言编写的一组指令的集合。...
    c5fc16271aee阅读 3,304评论 0 2
  • 本文主要讲了java中多线程的使用方法、线程同步、线程数据传递、线程状态及相应的一些线程函数用法、概述等。 首先讲...
    李欣阳阅读 7,186评论 1 15
  • 开始按照你的确定信念行事吧。 今天的内容是接续昨天内容中的练习的。可以参考看一下第45天早读的文章。你写下来自己正...
    然妈Miya阅读 3,047评论 0 0
  • 胡洋给我打电话的时候是下午两点,我刚吃过饭,她哭着跟我说,和徐林分手了。电话里她泣不成声,听不清说了什么,没说多久...
    艾米小姐阅读 4,093评论 0 1