多线程
并发和并行
实现方法
代码演示
方式一
package com.qiong.thread1;
public class MyThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println(getName() + "Hello World");
}
}
}
package com.qiong.thread1;
public class ThreadDemo1 {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.setName("线程一");
t2.setName("线程二");
//开启线程
t1.start();
t2.start();
/*
线程二Hello World
线程二Hello World
线程二Hello World
线程一Hello World
线程一Hello World
线程二Hello World
线程一Hello World
*/
}
}
方式二文章来源:https://www.toymoban.com/news/detail-792700.html
package com.qiong.thread2;
public class MyRun implements Runnable{
@Override
public void run() {
for (int i = 0; i < 20; i++) {
Thread thread = Thread.currentThread();
System.out.println(thread.getName() + "Hello World");
}
}
}
package com.qiong.thread2;
public class ThreadDemo {
public static void main(String[] args) {
MyRun mr = new MyRun();
Thread t1 = new Thread(mr);
Thread t2 = new Thread(mr);
t1.setName("线程1");
t2.setName("线程2");
t1.start();
t2.start();
/*
线程二Hello World
线程二Hello World
线程二Hello World
线程一Hello World
线程一Hello World
线程二Hello World
线程一Hello World
*/
}
}
方式三文章来源地址https://www.toymoban.com/news/detail-792700.html
package com.qiong.thread3;
import java.util.concurrent.Callable;
public class MyCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
//求1~100之间的和
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
return sum;
}
}
package com.qiong.thread3;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class ThreadDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallable mc = new MyCallable();
FutureTask<Integer> ft = new FutureTask<>(mc);
Thread t1 = new Thread(ft);
t1.start();
Integer result = ft.get();
System.out.println(result);//结果:5050
}
}
到了这里,关于Java多线程——并发和并行、实现方法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!