1.多线程建议使用Runnable不建议使用thread
使用方法:
package com.demo.redis;
public class MuliThread {
public static long t =0;
public static class changeT implements Runnable{
private long to;
public changeT(long to) {
this.to = to;
}
@Override
public void run() {
while (true) {
MuliThread.t =to;
Thread.yield();
}
}
}
public static class ReadT implements Runnable{
@Override
public void run() {
while (true) {
long tmp =MuliThread.t;
System.out.println(tmp);
Thread.yield();
}
}
}
public static void main(String[] args) {
new Thread(new changeT(111L)).start();
new Thread(new changeT(68L)).start();
new Thread(new changeT(-58L)).start();
new Thread(new changeT(-1L)).start();
new Thread(new changeT(31L)).start();
new Thread(new ReadT()).start();
}
}
2.线程间使用wait()和notify()控制
停止线程用Thread.yield(); 不要用Thread.stop();
3.线程的suspend()是将线程挂起,resume()是唤醒继续执行。
不建议使用因为线程挂起并不释放锁。导致其他线程等待。
4.thread.setDeamon()将一个线程设置为守护线程。
随着主线程结束而结束。
5.java设置线程优先级
t1.setPriority(1); 1-9 越大线程的优先级越高
6.synchronized程序间的线程同步、确保线程安全,采用加锁的方式。synchronized将多线程改为串行执行。
public void run() {
synchronized (this) {
while (true) {
System.out.println("R9=" + i++);
}
}
}
7.多线程环境下:
ArrayList 线程不安全 ,采用 Vector代替
HashMap线程不安全,用ConcurrentHashMap代替
8.在多线程中有多种方法让线程按特定顺序执行,你可以用线程类的join()方法在一个线程中启动另一个线程,另外一个线程完成该线程继续执行。
9.线程池的使用;
Java通过Executors提供四种线程池,分别为:
newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。
newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
public static void main(String[] args) {
ExecutorService poolExecutorService = Executors.newFixedThreadPool(300);
List<Callable<Void>> list = new ArrayList<Callable<Void>>();
for (int i = 0; i < 100; i++) {
final int index = i;
list.add(new Callable<Void>() {
@Override
public Void call() throws Exception {
System.out.println(index);
return null;
}
});
}
try {
poolExecutorService.invokeAll(list);
System.out.println("down");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
JAVA多线程
最新推荐文章于 2022-08-14 22:16:23 发布