并行和并发有什么区别?
-
并行是指两个或者多个事件在同一时刻发生;而并发是指两个或多个事件在同一时间间隔发生。 -
并行是在不同实体上的多个事件,并发是在同一实体上的多个事件。 -
在一台处理器上“同时”处理多个任务,在多台处理器上同时处理多个任务。如hadoop分布式集群。
线程和进程的区别?
代码如下
方式一:
package Java.Thread;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class TestThread2 extends Thread {
private String url;
private String name;
public TestThread2(String url,String name){
this.url=url;
this.name=name;
}
@Override
public void run() {
WebDownloader downloader = new WebDownloader();
downloader.download(url,name);
System.out.println("下载了文件名"+name);
}
public static void main(String[] args) {
TestThread2 t1 = new TestThread2("https://c-ssl.duitang.com/uploads/blog/202008/20/20200820180927_dfzpj.thumb.300_300_c.jpg","1.jpg");
TestThread2 t2 = new TestThread2("https://c-ssl.duitang.com/uploads/item/202004/06/20200406193332_levbg.thumb.300_300_c.jpg","2.jpg");
TestThread2 t3 = new TestThread2("https://c-ssl.duitang.com/uploads/item/202004/27/20200427160432_mhjwn.thumb.300_300_c.jpg","3.jpg");
t1.start();
t2.start();
t3.start();
}
}
class WebDownloader {
public void download(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
}
catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常");
}
}
}
方式二
package Java.Thread;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class TestThread3 implements Runnable {
private String url;
private String name;
public TestThread3(String url,String name){
this.url=url;
this.name=name;
}
@Override
public void run() {
WebDownLoader2 downLoader2 = new WebDownLoader2();
downLoader2.download(url,name);
System.out.println("下载了文件名" + name);
}
public static void main(String[] args) {
TestThread3 t1= new TestThread3("https://dl.stream.qqmusic.qq.com/C400003qyCb24Rhq7G.m4a?guid=1009329214&vkey=EBAD796F5C4C03506E5A1AECD46DD5903E129E67F83DE2E68EF83DE43ED7A47C5AF920D9A762313F3DDBD776389A0E8BD53E181FF50F375B&uin=1064432866&fromtag=66","水山少年梦.mp3");
TestThread2 t2 = new TestThread2("http://img1.gamedog.cn/2021/04/23/5649562-2104231049560.jpg","2.jpg");
TestThread2 t3 = new TestThread2("http://img1.gamedog.cn/2021/04/23/5649562-2104231045460.jpg","3.jpg");
new Thread(t1).start();
new Thread(t2).start();
new Thread(t3).start();
}
}
class WebDownLoader2{
public void download(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
}
catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常");
}
}
}
|