2023.1.11 打卡第二天
Java 多线程 1
/**
* @author jiang_star
* @date 2023.1.11
*/
public class Main {
public static void main(String[] args) throws InterruptedException {
/**
* 模拟并发
*/
Thread t = new Thread() {
public void run() {
System.out.println("thread run");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
int n = 0;
while (! isInterrupted()) {
n ++;
System.out.println(n + " hello!");
}
System.out.println("thread end.");
}
};
System.out.println("main start...");
t.setDaemon(true); //设置守护线程:在JVM中,所有非守护线程都执行完毕后,无论有没有守护线程,虚拟机都会自动退出。
t.start(); //开启线程
Thread.sleep(5000); //线程休眠
t.interrupt(); //中断线程
t.setPriority(5); //优先级 1-10
try {
Thread.sleep(2000);
} catch (InterruptedException e) {}
try {
t.join(); // 等待t线程结束
} catch (InterruptedException e) {
System.out.println("interrupted!");
}
/**
* 线程同步,保证原子性,为对象加锁解锁
*/
synchronized(lock) {
n = n + 1;
}
System.out.println("main end.");
}
}
//1.直接新建一个线程
/**
* Thread t = new Thread();
* t.start();
*/
//2.lambda公式
/**
* Thread t = new Thread(() -> {
* System.out.println("new thread 3");
* });
*/
//3.实现Runnable
/**
* Thread t = new Thread(new MyRunnable());
*/
class MyRunnable implements Runnable {
@Override
public void run () {
System.out.println("new thread 2");
}
}
//4.继承Thread
/**
* Thread t = new MyThread();
*/
class MyThread extends Thread {
@Override
public void run() {
System.out.println("new thread 1");
}
}
P2P 应用
纯P2P架构
- 没有(或极少)一直运行的服务器
- 任意端系统都可以直接通信
- 利用peer的服务能力
- Peer节点间歇上网,每次ip地址都有可能变化