美文网首页
Java多线程(一)

Java多线程(一)

作者: 一杯清凉的水 | 来源:发表于2018-03-21 22:26 被阅读0次

    念你的时光比相爱长


    Java多线程(一)

    继承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 访问同一资源代码的时候!!!

    参考资料:

    相关文章

      网友评论

          本文标题:Java多线程(一)

          本文链接:https://www.haomeiwen.com/subject/gagnqftx.html