Java面试知识点:多线程
生活随笔
收集整理的這篇文章主要介紹了
Java面试知识点:多线程
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
問題: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 {@Overridepublic 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> {@Overridepublic 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();@Overridepublic 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();@Overridepublic 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;}@Overridepublic 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;}@Overridepublic 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) {}@Overridepublic 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;}@Overridepublic 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) {}@Overridepublic 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);@Overridepublic void run() {try {semaphore.acquire();System.out.println("獲得了通行證開始行駛");Thread.sleep(2000);System.out.println("歸還通行證");} catch (InterruptedException e) {e.printStackTrace();}} }總結
以上是生活随笔為你收集整理的Java面试知识点:多线程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 小白学JAVA,与你们感同身受,JAVA
- 下一篇: 最小生成树——普里姆算法和克鲁斯卡尔算法