java 运用多线程
时间: 2023-11-29 08:46:55 浏览: 37
Java中的多线程可以通过继承Thread类或实现Runnable接口来实现。以下是两个Java多线程的例子:
1. 多线程下载文件并显示进度条
```java
import java.io.*;
import java.net.*;
public class DownloadFile extends Thread {
private String url;
private String fileName;
private int threadNum;
private int startPos;
private int endPos;
private int curPos;
private int fileSize;
private int downloadedSize;
public DownloadFile(String url, String fileName, int threadNum) {
this.url = url;
this.fileName = fileName;
this.threadNum = threadNum;
}
public void run() {
try {
URL fileUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) fileUrl.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setRequestProperty("Range", "bytes=" + startPos + "-" + endPos); int responseCode = conn.getResponseCode();
if (responseCode == 206) {
fileSize = conn.getContentLength();
InputStream is = conn.getInputStream();
RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
raf.seek(startPos);
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
raf.write(buffer, 0, len);
curPos += len;
downloadedSize += len;
}
is.close();
raf.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String url = "http://example.com/file.zip";
String fileName = "file.zip";
int threadNum = 5;
try {
URL fileUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) fileUrl.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
int fileSize = conn.getContentLength();
int blockSize = fileSize / threadNum;
for (int i = 0; i < threadNum; i++) {
int startPos = i * blockSize;
int endPos = (i + 1) * blockSize - 1;
if (i == threadNum - 1) {
endPos = fileSize - 1;
}
DownloadFile downloadFile = new DownloadFile(url, fileName, threadNum);
downloadFile.startPos = startPos;
downloadFile.endPos = endPos;
downloadFile.start();
}
int curPos = 0;
while (curPos < fileSize) {
System.out.print("[");
int percent = curPos * 100 / fileSize;
for (int i = 0; i < percent / 2; i++) {
System.out.print("=");
}
for (int i = percent / 2; i < 50; i++) {
System.out.print(" ");
}
System.out.print("] " + percent + "%\r");
Thread.sleep(1000);
curPos = 0;
for (int i = 0; i < threadNum; i++) {
curPos += downloadFile.curPos;
}
}
System.out.println();
System.out.println("Download completed!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
2. 多线程控制小球运动
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BallGame extends JFrame implements Runnable {
private int x = 50;
private int y = 50;
private int size = 50;
private Color color = Color.RED;
private int speed = 10;
private boolean isRunning = true;
public BallGame() {
setTitle("Ball Game");
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JLabel sizeLabel = new JLabel("Size:");
JSlider sizeSlider = new JSlider(JSlider.HORIZONTAL, 10, 100, 50);
sizeSlider.setMajorTickSpacing(10);
sizeSlider.setMinorTickSpacing(5);
sizeSlider.setPaintTicks(true);
sizeSlider.setPaintLabels(true);
sizeSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
size = sizeSlider.getValue();
}
});
JLabel colorLabel = new JLabel("Color:");
JComboBox<String> colorComboBox = new JComboBox<String>();
colorComboBox.addItem("Red");
colorComboBox.addItem("Green");
colorComboBox.addItem("Blue");
colorComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String colorString = (String) colorComboBox.getSelectedItem();
if (colorString.equals("Red")) {
color = Color.RED;
} else if (colorString.equals("Green")) {
color = Color.GREEN;
} else if (colorString.equals("Blue")) {
color = Color.BLUE;
}
}
});
panel.add(sizeLabel);
panel.add(sizeSlider);
panel.add(colorLabel);
panel.add(colorComboBox);
add(panel, BorderLayout.NORTH);
add(new DrawPanel(), BorderLayout.CENTER);
setVisible(true);
}
public void run() {
while (isRunning) {
if (x < 0 || x > getWidth() - size) {
speed = -speed;
}
x += speed;
repaint();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private class DrawPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(color);
g.fillOval(x, y, size, size);
}
}
public static void main(String[] args) {
BallGame ballGame = new BallGame();
Thread thread = new Thread(ballGame);
thread.start();
}
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)