我正在尝试制作一个下载文件的程序。在下载文件时,需要有一个从开始到结束的基本计数器。这两个函数需要在自己的线程中。我已经创建了一个方法/线程来下载文件。我无法弄清楚如何制作一个基本的计数器。没有什么花哨但它需要计数,只显示当前的数字。任何帮助将不胜感激。
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static myutilites.methods.*;
public class Downloader
{
public static void main(String[] args) throws IOException
{
String filename = "Nexus5MahdiRom.zip";
URL link = new URL(
"http://files.mahdi-rom.com/OnePlus%20One/"
+ "OnePlus%20One%20Builds/mahdi-2.7-bacon-20140903.zip");
Thread t1 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
downloadFile(filename,link);
} catch (IOException e)
{
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable()
{
@Override
public void run()
{
try {
counter(link, t1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t1.start();
println("Downloading File...");
}
public void getScreenSize()
{
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
println("width = " + d.width + " height = " + d.height);
}
public static void downloadFile(String fileName, URL link) throws IOException
{
InputStream in = new BufferedInputStream(link.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte [] buf = new byte[1024];
int n = 0;
int count = 0;
while (-1 !=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
println(count);
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(response);
fos.close();
println("Download Finished");
}
public static void locate(int row, int col)
{
System.out.print("\033["+row+";"+col+"H");
}
public static int counter(URL link, Thread t1) throws IOException
{
int count = 0;
link.openConnection();
while(t1.isAlive())
{
count++;
return count;
}
return count;
}
}
答案 0 :(得分:0)
在AtomicInteger上使用getAndIncrement
或incrementAndGet
,这是一个线程安全的计数器(计数器初始化为0,如果两个线程同时调用incrementAndGet
那么你'保证计数器将返回1到1个线程,2个返回到另一个线程,并且最终状态为2)