问题:Java面试知识点:多线程
答案:
1.线程
代码如下:
package com.xy;
/**
* @ProjectName: day01
* @Package: com.xy
* @ClassName: test01
* @Author: 杨路恒
* @Description:
* @Date: 2021/8/25 0025 16:57
* @Version: 1.0
*/
public class test01 {
public static void main(String[] args) {
MyThread myThread=new MyThread();
MyThread myThread1=new MyThread();
myThread.start();
myThread1.start();
}
}
public class test02 {
public static void main(String[] args) {
MyRunnable mr=new MyRunnable(); //创建了一个参数对象
Thread t=new Thread(mr); //创建了一个线程对象,并把参数传递给这个线程
t.start();
MyRunnable mr1=new MyRunnable();
Thread t1=new Thread(mr1); //创建了一个线程对象,并把参数传递给这个线程
t1.start();
}
}
public class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("第二种方式启动线程"+i);
}
}
}
public class test03 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallable mc=new MyCallable(); //线程开启之后需要执行里面的call方法
//可以获取线程执完毕之后的结果,也可以作为参数传递给Thread对象
FutureTask<String> ft=new FutureTask<>(mc);
Thread t=new Thread(ft);
System.out.println(t.getName());
t.start();
String s = ft.get();
System.out.println(s);
MyCallable mc1=new MyCallable(); //线程开启之后需要执行里面的call方法
//可以获取线程执完毕之后的结果,也可以作为参数传递给Thread对象
FutureTask<String> ft1=new FutureTask<>(mc);
// Thread t1=new Thread(ft,"恒大大");
Thread t1=new Thread(ft);
t1.start();
t1.setName("杨大大");
System.out.println(t1.getName());
String s1 = ft.get();
System.out.println(s);
}
}
public class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
for (int i = 0; i < 100; i++) {
System.out.println("第三种启动线程方式"+i);
Thread.sleep(1000);
}
return "成功";
}
}
2.同步代码块、同步方法
代码如下:
public class test04 {
public static void main(String[] args) {
MyRunnable1 mr=new MyRunnable1();
Thread t=new Thread(mr);
Thread t1=new Thread(mr);
Thread t2=new Thread(mr);
t.start();
t1.start();
t2.start();
}
}
class MyRunnable1 implements Runnable{
private int ticket=100;
Object obj=new Object();
@Override
public void run() {
while (true){
synchronized (obj){ //同步代码块
if (ticket>0){
System.out.println(Thread.currentThread().getName()+"卖第"+ticket+"张票");
ticket--;
}
else {
return;
}
}
}
}
}
package com.xy;
/**
* @ProjectName: day01
* @Package: com.xy
* @ClassName: test04
* @Author: 杨路恒
* @Description:
* @Date: 2021/8/26 0026 16:51
* @Version: 1.0
*/
public class test05 {
public static void main(String[] args) {
MyRunnable2 mr = new MyRunnable2();
Thread t = new Thread(mr);
Thread t1 = new Thread(mr);
Thread t2 = new Thread(mr);
t.start();
t1.start();
t2.start();
}
}
class MyRunnable2 implements Runnable {
private int ticket = 100;
Object obj = new Object();
@Override
public void run() {
while (true) {
ticket();
}
}
public synchronized void ticket() {
if (ticket > 0) {
System.out.println(Thread.currentThread().getName() + "卖第" + ticket + "张票");
ticket--;
} else {
return;
}
}
}
3.原子性、CAS算法
代码如下:
package com.xy;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @ProjectName: day01
* @Package: com.xy
* @ClassName: test16原子性
* @Author: 杨路恒
* @Description:
* @Date: 2021/8/29 0029 14:08
* @Version: 1.0
*/
public class test16原子性 {
public static void main(String[] args) {
AtomicInteger ac=new AtomicInteger();
System.out.println(ac);
AtomicInteger ac1=new AtomicInteger(6);
System.out.println(ac1);
}
}
package com.xy;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @ProjectName: day01
* @Package: com.xy
* @ClassName: test17原子性
* @Author: 杨路恒
* @Description:
* @Date: 2021/8/29 0029 14:10
* @Version: 1.0
*/
public class test17原子性 {
public static void main(String[] args) {
AtomicInteger ac=new AtomicInteger(6);
System.out.println(ac.get());
int i = ac.getAndIncrement();
int i1 = ac.incrementAndGet();
System.out.println(i);
System.out.println(i1);
int i2 = ac.addAndGet(6);
System.out.println(i2);
int i3 = ac.getAndSet(6);
System.out.println(i);
}
}
4.线程池
代码如下:
package com.xy;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @ProjectName: day01
* @Package: com.xy
* @ClassName: test10线程池
* @Author: 杨路恒
* @Description:
* @Date: 2021/8/27 0027 19:54
* @Version: 1.0
*/
public class test10线程池 {
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService= Executors.newCachedThreadPool();
executorService.submit(()->{
System.out.println(Thread.currentThread().getName()+"启动");
});
Thread.sleep(2000);
executorService.submit(()->{
System.out.println(Thread.currentThread().getName()+"启动");
});
Thread.sleep(2000);
executorService.shutdown();
}
}
public class test13线程池 {
public static void main(String[] args) {
ThreadPoolExecutor pool=new ThreadPoolExecutor(2,
5,2,
TimeUnit.SECONDS,new ArrayBlockingQueue<>(10),
Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
pool.submit(new MyRunnable3());
pool.submit(new MyRunnable3());
pool.shutdown();
}
}
public class test14线程池 {
public static void main(String[] args) {
ThreadPoolExecutor pool=new ThreadPoolExecutor(1,
2,2,
TimeUnit.SECONDS,new ArrayBlockingQueue<>(1),
Executors.defaultThreadFactory(),
// new ThreadPoolExecutor.AbortPolicy());
// new ThreadPoolExecutor.DiscardPolicy());
// new ThreadPoolExecutor.DiscardOldestPolicy());
new ThreadPoolExecutor.CallerRunsPolicy());
for (int i = 0; i < 5; i++) {
int y=i;
pool.submit(()->{
System.out.println(Thread.currentThread().getName()+":"+y);
});
}
pool.shutdown();
}
}
5.阻塞队列
代码如下:
public class test08阻塞队列 {
public static void main(String[] args) {
ArrayBlockingQueue<String> list=new ArrayBlockingQueue<>(1);
Cooker1 c=new Cooker1(list);
Foodie1 f=new Foodie1(list);
c.start();
f.start();
}
}
public class test09阻塞队列 {
public static void main(String[] args) throws InterruptedException {
ArrayBlockingQueue<String> list=new ArrayBlockingQueue<>(1);
list.put("汉堡包");
System.out.println(list.take());
}
}
public class Cooker1 extends Thread{
ArrayBlockingQueue<String> list;
public Cooker1(ArrayBlockingQueue<String> list) {
this.list = list;
}
@Override
public void run() {
while (true){
try {
list.put("汉堡包");
System.out.println("生产者");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Foodie1 extends Thread{
ArrayBlockingQueue<String> list;
public Foodie1(ArrayBlockingQueue<String> list) {
this.list = list;
}
@Override
public void run() {
while (true){
try {
String take = list.take();
System.out.println("消费者");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
生产者、消费者:
public class Cooker extends Thread {
private Desk desk;
public Cooker(Desk desk) {
}
@Override
public void run() {
while (true){
synchronized (desk.getLock()){
if (desk.getCount()==0){
break;
}
else {
if (!desk.isFlag()){
System.out.println("生产者");
desk.setFlag(true);
desk.getLock().notifyAll();
}
else {
try {
desk.getLock().wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
}
public class Desk {
private boolean flag=false;
private int count=100;
private final Object lock=new Object();
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public Object getLock() {
return lock;
}
@Override
public String toString() {
return "Desk{" +
"flag=" + flag +
", count=" + count +
", lock=" + lock +
'}';
}
public Desk(boolean flag, int count) {
this.flag = flag;
this.count = count;
}
public Desk() {
this(true,100);
}
}
public class Foodie extends Thread{
private Desk desk;
public Foodie(Desk desk) {
}
@Override
public void run() {
while (true){
synchronized (desk.getLock()){
if (desk.getCount()==0){
break;
}
else {
if (desk.isFlag()){
System.out.println("消费者");
desk.setFlag(false);
desk.getLock().notifyAll();
desk.setCount(desk.getCount()-1);
}
else {
try {
desk.getLock().wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
}
package com.xy;
/**
* @ProjectName: day01
* @Package: com.xy
* @ClassName: test07生产者消费者
* @Author: 杨路恒
* @Description:
* @Date: 2021/8/27 0027 17:29
* @Version: 1.0
*/
public class test07生产者消费者 {
public static void main(String[] args) {
Desk desk=new Desk();
Foodie f=new Foodie(desk);
Cooker c=new Cooker(desk);
f.start();
c.start();
}
}
6.HashMap、HashTable、ConcurrentHashMap、CountDownLatch、
Semaphore
代码如下:
package com.xy;
import java.util.Hashtable;
import java.util.concurrent.ConcurrentHashMap;
/**
* @ProjectName: day01
* @Package: com.xy
* @ClassName: test18并发工具类
* @Author: 杨路恒
* @Description:
* @Date: 2021/8/29 0029 18:47
* @Version: 1.0
*/
public class test20ConcurrentMap {
public static void main(String[] args) throws InterruptedException {
ConcurrentHashMap<String,String> map=new ConcurrentHashMap<>();
Thread t1=new Thread(()->{
for (int i = 0; i < 25; i++) {
map.put(i+"",i+"");
}
});
Thread t2=new Thread(()->{
for (int i = 25; i < 51; i++) {
map.put(i+"",i+"");
}
});
t1.start();
t2.start();
Thread.sleep(1000);
for (int i = 0; i < 51; i++) {
System.out.println(map.get(i+""));
}
}
}
package com.xy;
import java.util.concurrent.CountDownLatch;
/**
* @ProjectName: day01
* @Package: com.xy
* @ClassName: test21CountDownLatch
* @Author: 杨路恒
* @Description:
* @Date: 2021/8/30 0030 20:49
* @Version: 1.0
*/
public class test21CountDownLatch {
public static void main(String[] args) {
CountDownLatch countDownLatch=new CountDownLatch(3);
MotherThread motherThread=new MotherThread(countDownLatch);
motherThread.start();
ChildThread1 t1=new ChildThread1(countDownLatch);
t1.setName("杨大大");
ChildThread2 t2=new ChildThread2(countDownLatch);
t2.setName("恒大大");
ChildThread3 t3=new ChildThread3(countDownLatch);
t3.setName("路大大");
t1.start();
t2.start();
t3.start();
}
}
package com.xy;
import java.util.concurrent.Semaphore;
/**
* @ProjectName: day01
* @Package: com.xy
* @ClassName: test22Semaphore
* @Author: 杨路恒
* @Description:
* @Date: 2021/8/30 0030 21:07
* @Version: 1.0
*/
public class test22Semaphore {
public static void main(String[] args) {
SemaphoreRunnable sr=new SemaphoreRunnable();
for (int i = 0; i < 100; i++) {
new Thread(sr).start();
}
}
}
class SemaphoreRunnable implements Runnable{
private Semaphore semaphore=new Semaphore(2);
@Override
public void run() {
try {
semaphore.acquire();
System.out.println("获得了通行证开始行驶");
Thread.sleep(2000);
System.out.println("归还通行证");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}