public class ThreadTest extends Thread{
@Override
public void run() {
//run方法线程体
for(int i=0;i<10;i++)
System.out.println("多线程------");
}
public static void main(String[] args) {
ThreadTest a=new ThreadTest();
a.start();
for(int i=0;i<1000;i++){
System.out.println("主线程");
}
}
}
文件下载包
public class ThreadTest extends Thread{
private String url;
private String file;
public ThreadTest(String url,String file) {
//构造函数
this.url=url;
this.file=file;
}
@Override
public void run() {
WebDownLoader down=new WebDownLoader();
down.download(url,file);
System.out.println("下载完成:"+file);
}
public static void main(String[] args) {
ThreadTest down1=new ThreadTest("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3769272980,4240368075&fm=26&gp=0.jpg","01.jpg");
ThreadTest down2=new ThreadTest("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1393799263,3304349115&fm=26&gp=0.jpg","02.jpg");
ThreadTest down3=new ThreadTest("https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=134213255,2108409328&fm=26&gp=0.jpg","03.jpg");
down1.start();
down2.start();
down3.start();
}
}
class WebDownLoader{
//下载器
public void download(String url,String file){
try {
FileUtils.copyURLToFile(new URL(url),new File(file));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO错误");
}
}
}
public class RunnableTest implements Runnable{
@Override
public void run() {
for(int i=0;i<10;i++)
System.out.println("111");
}
public static void main(String[] args) {
//创建Runnable实现接口类
Runnable test=new RunnableTest();
//创建线程对象,通过线程对象开启线程
Thread thread=new Thread(test);
thread.start();
for(int i=0;i<100;i++)
System.out.println("222");
}
}
好处
实现过程
public class CallableTest implements Callable<Boolean> {
@Override
public Boolean call() throws Exception {
for(int i=0;i<100;i++)
System.out.println("run");
return true;
}
public static void main(String[] args) throws Exception{
CallableTest c1=new CallableTest();
CallableTest c2=new CallableTest();
CallableTest c3=new CallableTest();
CallableTest callable=new CallableTest();
//创建执行服务
ExecutorService ser= Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> r1=ser.submit(c1);
Future<Boolean> r2=ser.submit(c2);
Future<Boolean> r3=ser.submit(c3);
//获取结果
Boolean res1=r1.get();
Boolean res2=r2.get();
Boolean res3=r3.get();
//关闭服务
ser.shutdown();
}
}
另一种启动方法:FutureTask
//借助futureTask 类
FutureTask<integer> futureTask = new FutureTask(new Thread());
new Thread(futureTask,"name").start();
//返回结果
Integer integer=futureTask.get();
//静态代理
public class StaticProxy {
public static void main(String[] args) {
Poxy poxy=new Poxy(new You());
poxy.HappyMarry();
}
}
//建立一个接口
interface Marry{
public void HappyMarry();
}
//真实对象
class You implements Marry{
@Override
public void HappyMarry() {
System.out.println("I am Marray");
}
}
//代理对象
class Poxy implements Marry{
private You you;
Poxy(You you){
this.you=you;
}
@Override
public void HappyMarry() {
System.out.println("brfore marry");
you.HappyMarry();
System.out.println("after marry");
}
}
()->表达式;
函数式接口:
public class LambdaTest {
//3.静态内部类
static class Two implements Father{
@Override
public void lambda() {
System.out.println("静态内部类");
}
}
public static void main(String[] args) {
//4.局部内部类
class Three implements Father{
@Override
public void lambda() {
System.out.println("局部内部类");
}
}
Father father=null;
father=new One();
father.lambda();
father=new Two();
father.lambda();
father=new Three();
father.lambda();
father=new Father() {
//匿名内部类
@Override
public void lambda() {
System.out.println("匿名内部类");
}
};
father.lambda();
//lambda表达式
father=()->{
System.out.println("Lambda表达式");
};
father.lambda();
}
}
//1.定义一个接口
interface Father{
void lambda();
}
//2.实现一个类
class One implements Father{
@Override
public void lambda() {
System.out.println("一般实现方法");
}
}
简化Lambda表达式
//原表达式
Father2 father2=(int n)->{
System.out.println("简化"+n);
};
father2.lambda(0);
//去掉参数类型
father2=(n)->{
System.out.println("简化"+n);
};
father2.lambda(1);
//去掉括号
father2=n->{
System.out.println("简化"+n);
};
father2.lambda(2);
//去掉花括号
father2=n->System.out.println("简化"+n);
father2.lambda(3);
//线程停止
public class StopTest implements Runnable{
//设置一个标志位
private boolean flag=true;
@Override
public void run() {
int i=0;
while(flag){
System.out.println("Runinng-----"+i++);
}
}
//设置一个公开方法停止线程,转换标志位
public void stop(){
this.flag=false;
}
public static void main(String[] args) {
StopTest stop=new StopTest();
new Thread(stop).start();
for(int i=0;i<100;i++){
if(i==99)
stop.stop();
System.out.println("main"+i);
}
}
}
//获取当前系统时间
public class SleepTest {
public void printCurrentTime(){
Date currentTime=null;
while(true){
try {
Thread.sleep(1000);
}catch (Exception a){
a.printStackTrace();
}
//获取当前系统时间
currentTime=new Date(System.currentTimeMillis());
System.out.println(new SimpleDateFormat("HH:mm:ss").format(currentTime));
}
}
public static void main(String[] args) {
new SleepTest().printCurrentTime();
}
}
public class YieldTest {
public static void main(String[] args) {
myYield yield=new myYield();
new Thread(yield,"a").start();
new Thread(yield,"b").start();
}
}
class myYield implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+":start");
Thread.yield();//礼让
System.out.println(Thread.currentThread().getName()+":stop");
}
}
public class JoinTest implements Runnable{
@Override
public void run() {
for(int i=0;i<10;i++){
try {
Thread.sleep(1000);
}catch (Exception a){
a.printStackTrace();
}
System.out.println("VIP线程---"+i);
}
}
public static void main(String[] args) throws Exception{
//插入线程开始
JoinTest join=new JoinTest();
Thread thread=new Thread(join);
thread.start();
//主线程
for(int i=0;i<1000;i++){
if(i==200)
thread.join();
System.out.println("main---"+i);
}
}
}
//线程状态
public class StateTest {
public static void main(String[] args) {
Thread thread = new Thread(()->{
for(int i=0;i<10;i++){
try {
Thread.sleep(1000);
}catch (Exception e){
e.printStackTrace();
}
}
});
//检测状态
Thread.State state = thread.getState();
System.out.println(state); //NEW
//启动
thread.start();
state=thread.getState();
System.out.println(state); //RUN
while (state!=Thread.State.TERMINATED){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//只要不停止就输出状态
state=thread.getState();
System.out.println(state);
}
System.out.println(state);
}
}
public class DaemonTest {
public static void main(String[] args) {
God god=new God();
You you=new You();
Thread thread=new Thread(god);
thread.setDaemon(true); //默认式false,默认都是用户线程
thread.start();
new Thread(you).start(); //用户线程
}
}
class God implements Runnable{
@Override
public void run() {
while(true){
System.out.println("I see you");
}
}
}
class You implements Runnable{
@Override
public void run() {
for(int i=0;i<365;i++){
System.out.println("aLive:"+i);
}
System.out.println("dead!!!");
}
}
###GUC里的安全类型的集合
//测试GUC安全类型的集合
public class GUCTest {
public static void main(String[] args) {
CopyOnWriteArrayList<String> list=new CopyOnWriteArrayList<String>();
for(int i=0;i<1000;i++){
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(3000);
System.out.println(list.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
产生死锁的四个条件:
public class LockTest {
public static void main(String[] args) {
Ticket ticket=new Ticket();
new Thread(ticket).start();
new Thread(ticket).start();
new Thread(ticket).start();
}
}
class Ticket implements Runnable{
private int ticketNum=10;
//定义lock锁
private ReentrantLock lock=new ReentrantLock();
@Override
public void run() {
while(true){
try {
lock.lock();
if(ticketNum>0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.ticketNum--);
}else
break;
}finally {
lock.unlock();
}
}
}
}
//生产者消费者----管程法
public class PCTest {
public static void main(String[] args) {
//生产者,消费者,产品,缓冲区
SynContainer synContainer=new SynContainer();
new Thread(new Producter(synContainer)).start();
new Thread(new Consumer(synContainer)).start();
}
}
//生产者
class Producter implements Runnable{
SynContainer synContainer;
public Producter(SynContainer synContainer) {
this.synContainer = synContainer;
}
@Override
public void run() {
for(int i=0;i<100;i++){
synContainer.push(new Chichen(i));
System.out.println("生产了:"+i+"只鸡");
}
}
}
//消费者
class Consumer implements Runnable{
SynContainer synContainer;
public Consumer(SynContainer synContainer) {
this.synContainer = synContainer;
}
@Override
public void run() {
for(int i=0;i<100;i++){
Chichen num=synContainer.pop();
System.out.println("消费了--->"+num.id+"只鸡");
}
}
}
//产品
class Chichen{
int id;
public Chichen(int id) {
this.id = id;
}
}
//缓存区
class SynContainer{
//需要一个容器大小
Chichen[] chichens=new Chichen[10];
int count=0;
//生产者放入产品
public synchronized void push(Chichen chichen){
//如果容器满了,需要等待消费者消费
if(count==chichens.length){
//通知消费者消费,生产者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果没有满,我们就丢入产品
chichens[count]=chichen;
count++;
//通知消费者消费
this.notifyAll();
}
//消费者消费产品
public synchronized Chichen pop(){
//判断能否消费
if(count==0){
//等待生产者生产,消费者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//可以消费
count--;
Chichen chichenReturn=chichens[count];
//通知生产者生产
this.notifyAll();
return chichenReturn;
}
}
package com.company;
//生产者消费者---》信号灯法
public class PCTeo {
public static void main(String[] args) {
TV tv=new TV();
new Thread(new Player(tv)).start();
new Thread(new Watch(tv)).start();
}
}
//生产者--》演员
class Player implements Runnable{
TV tv;
public Player(TV tv) {
this.tv = tv;
}
@Override
public void run() {
for(int i=0;i<10;i++){
if(i%2==0){
tv.play("节目1");
}else
tv.play("节目2");
}
}
}
//消费者--》观众
class Watch implements Runnable{
TV tv;
public Watch(TV tv) {
this.tv = tv;
}
@Override
public void run() {
for(int i=0;i<10;i++)
tv.watch();
}
}
//节目
class TV{
//演员表演,观众等待
//观众观看,演员等待
String voice;//表演的节目
boolean flag=true;
//表演
public synchronized void play(String voice){
if(!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("表演了:"+voice);
//通知观众观看
this.notifyAll();
this.voice=voice;
this.flag=!this.flag;
}
//观看
public synchronized void watch(){
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观看了:"+voice);
this.flag=!this.flag;
//通知表演者表演
this.notifyAll();
}
}
线程池:
//测试线程池
public class PoolTest {
public static void main(String[] args) {
//1.创建服务。创建线程池
//newFixedThreadPool参数是线程池大小
ExecutorService service= Executors.newFixedThreadPool(10);
//2.执行
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
//3.关闭连接
service.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
//获得CPU的核数
System.out.println(Runtime.getRuntime().availableProcessors());
private Lock lock=new ReentrantLock();
private Condition condition1 = lock.newCondition();
private Condition condition2= lock.newCondition();
private Condition condition3 = lock.newCondition();
//使用格式
//上锁
lock.lock();
//等待
condition1.await();
//唤醒第二个线程
condition2.signal();
//解锁
lock.unlock();
HashSet底层是HashMap
同理set也存在并发修改异常:ConcurrentModificationException
解决方法:
//线程计数器
public class test01 {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch=new CountDownLatch(6);
for (int i = 0; i <6 ; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName());
latch.countDown();
},String.valueOf(i)).start();
}
latch.await();
System.out.println("结束了");
}
}
//CyclicBarrier测试
public class Test02 {
public static void main(String[] args) {
//主线程
CyclicBarrier cyclicBarrier=new CyclicBarrier(7,()->{
System.out.println("召唤神龙!!!");
});
for (int i = 0; i < 7; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"get one!");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
},String.valueOf(i)).start();
}
}
}
//测试Semaphore
public class test03 {
public static void main(String[] args) {
//线程数量
Semaphore semaphore=new Semaphore(3);
for (int i = 0; i <6; i++) {
new Thread(()->{
try {
//acquire得到
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"进入");
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName()+"离开");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
//release释放
semaphore.release();
}
},String.valueOf(i)).start();
}
}
}