Java from entry to the master Chapter 18 Multithreading

table of Contents

Two ways to achieve thread

Operating the thread method

Thread priority

Thread Synchronization


Two ways to achieve thread

Each program is a process, a process can have multiple threads, the thread is a process of the implementation process

  • Java.lang.Thread class inheritance
  • Implement java.lang.Runnable interface (java does not support multiple inheritance, the need to inherit from other classes they need to take advantage of multi-threaded interface)
  • Thread of the life cycle: birth state, ready state, running state, the wait state, dormant state, blocking state, the state of death

Operating the thread method

  • Sleep thread Thread.sleep (), sleep is a static method of the Thread milliseconds
  • Was added Thread.join thread (), after addition of the thread in the thread A, B, B is performed after executing A
  • Thread interrupt thread.interrupt (), triggered InterruptedException, normally closed database connections and socket connections and other operations in the catch. Run in a manner to promote the use of wireless loop, then a Boolean flag control loop is stopped.
  • Comity yield thread (), for multi-tasking operating system does not require the use of the operating system will automatically allocate CPU time slice

Thread priority

The system is always ready to select the next higher priority thread into the running state. High priority is not necessarily performed first, also depends on the operating system

Thread Synchronization

Multithreading resources are synchronized using a given time allowing only one thread access to shared resources, to a lock on resources

  • Sync block synchronized (), the resource will operate in sync blocks
  • Synchronization method, before adding synchronized modification of the method, an object must wait after the synchronization method is executed when the call is finished synchronization method
//继承Thread
package ex18_Thread;

public class ThreadTest extends Thread {
    private int count = 10;
    public void run() {  // 覆盖run()方法
        while (true) {
            System.out.print(count + " ");
            if (--count == 0)
                return;
        }
    }

    public static void main(String args[]) {
        ThreadTest t1 = new ThreadTest();
        ThreadTest t2 = new ThreadTest();
        t1.start();  // 线程执行调用start()
        t2.start();
    }

}

 

//使用Runnable接口实现多线程
package ex18_Thread;

import javax.swing.*;
import java.awt.*;
import java.net.URL;
import java.util.EmptyStackException;

public class SwingAndThread extends JFrame {
    private JLabel jl = new JLabel();  // 声明JLable对象
    private static Thread t;  //声明线程对象
    private int count = 0;  //声明计数变量
    private Container container = getContentPane();  //声明容器

    public SwingAndThread() {
        setBounds(100,100,1000,1000);  //绝对定位窗体大小和位置
        container.setLayout(null);  //不使用任何布局管理器
        URL url = SwingAndThread.class.getResource("/ex18_Thread/1.gif");  //获取图标url
        Icon icon = new ImageIcon(url);  //实例化一个icon
        jl.setIcon(icon);  //将图标放在标签中
        jl.setHorizontalAlignment(SwingConstants.LEFT); //将图片放在左边
//        jl.setBounds(10,10,500,500);  //设置标签位置和大小
        jl.setOpaque(true);  //设置不透明

        t = new Thread(new Runnable() {  //定义匿名内部类,该类实现Runnable接口
            @Override
            public void run() {  //重写run()
                while (count <= 500) {
                    jl.setBounds(count,10,500,500);
                    try {
                        Thread.sleep(1000);  //线程休眠1000毫秒
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    count += 4;
                    if (count == 500) {  //当其回到最右边时回到最左边
                        count = 10;
                    }
                }

            }
        });
        t.start();  //启用一个新线程start(), start()运行run()方法
        container.add(jl);
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

    }
    public static void main(String args[]) {
        new SwingAndThread();
    }


}

 

//线程的休眠
package ex18_Thread;

import javax.swing.*;
import java.awt.*;
import java.util.Random;

public class SleepMethodTest extends JFrame {
    private Thread t;
    private static Color[] color = {Color.BLACK, Color.BLUE,Color.CYAN,Color.RED};
    private static final Random rand = new Random();  //创建随机对象
    private static Color getC() {
        return color[rand.nextInt(color.length)];
    }

    public SleepMethodTest() {
        t = new Thread(new Runnable() {
            int x = 100;
            int y = 100;
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //获取组件绘图上下文对象
                    Graphics graphics = getGraphics();
                    graphics.setColor(getC());  //设置绘图颜色
                    graphics.drawLine(x, y+=10, 800, y);
                    if (y >= 800) {
                        y = 100;
                    }
                }
            }
        });
        t.start();
    }

    public static void main(String args[]) {
        init(new SleepMethodTest(),1000,1000);
    }

    //设置窗体的各种属性的方法
    public static void init(JFrame frame, int width, int height) {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(width, height);
        frame.setVisible(true);
    }

}

 

//线程的加入
package ex18_Thread;

import javax.swing.*;
import java.awt.*;

public class JoinTest extends JFrame {
    private Thread threadA;
    private Thread threadB;
    final JProgressBar jProgressBar = new JProgressBar();
    final JProgressBar jProgressBar1 = new JProgressBar();
    int count = 0;
    public JoinTest() {
        super();
        getContentPane().add(jProgressBar, BorderLayout.NORTH);
        getContentPane().add(jProgressBar1, BorderLayout.SOUTH);
        jProgressBar.setStringPainted(true);
        jProgressBar1.setStringPainted(true);
        //使用匿名内部类初始化Thread实例
        threadA = new Thread(new Runnable() {
            int count = 0;
            @Override
            public void run() {
                while (true) {
                    jProgressBar.setValue(count++);
                    try {
                        Thread.sleep(100);
                        threadB.join();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        threadA.start();

        threadB = new Thread(new Runnable() {
            int count = 0;
            @Override
            public void run() {
                while (true) {
                    jProgressBar1.setValue(count++);
                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (count + 1 == 100)
                        break;
                }
            }
        });
        threadB.start();

    }



    public static void main(String args[]) {
        init(new JoinTest(), 100,100);
    }

    //设置窗体的各种属性的方法
    public static void init(JFrame frame, int width, int height) {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(width, height);
        frame.setVisible(true);
    }
}

 

//线程的中断
package ex18_Thread;

import javax.swing.*;
import java.awt.*;

public class InterruptedSwing extends JFrame {
    Thread thread;

    public InterruptedSwing() {
        super();
        final JProgressBar progressBar = new JProgressBar();
        getContentPane().add(progressBar, BorderLayout.NORTH);
        progressBar.setStringPainted(true);
        thread = new Thread(new Runnable() {
            int count = 0;
            @Override
            public void run() {
                while (true) {
                    progressBar.setValue(count++);
                    try {
                        thread.sleep(1000);
                    } catch (InterruptedException e) {
                        System.out.println("当前程序被中断");
                        break;
                    }
                }


            }
        });
        thread.start();
        thread.interrupt();
    }

    public static void main(String[] args) {
        init(new InterruptedSwing(), 100, 100);
    }

    //设置窗体的各种属性的方法
    public static void init(JFrame frame, int width, int height) {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(width, height);
        frame.setVisible(true);
    }


}

 

 

 

Published 46 original articles · won praise 0 · Views 1017

Guess you like

Origin blog.csdn.net/weixin_37680513/article/details/103604387