简介
注:
- 程序:代码
- 进程 : 一个跑起来的程序
- 线程: 进程中多个任务
- 并发 : 1 打多
- 并行 : 多对多
如何查看自己电脑是几核的
Runtime runtime = Runtime.getRuntime ();
int i = runtime.availableProcessors ();
System.out.println (i);
创建线程的方法
继承Thread 或者实现runnable接口
Thread.currentThread ().getName () - 返回当前线程的名字
主线程的名字叫做main
使用继承方式的代码如下
public class StartCat {
public static void main( String[] args ) throws InterruptedException {
Cat cat = new Cat ();
cat.start ();
int n = 0;
while (n<40){
System.out.println ("132d" + (++n));
Thread.sleep (1000);
}
}
}
class Cat extends Thread {
int time = 0;
@Override
public void run() {
while (time < 60) {
System.out.println ("喵喵,我是小猫咪" + (++time) + Thread.currentThread ().getName ());
try {
Thread.sleep (1000);
} catch (InterruptedException e) {
e.printStackTrace ();
}
if (time == 7) {
break;
}
}
}
}
调用·Start方法是不调用run方法是因为要开启一个新的线程,而不是调用方法,start目的是起一个新线程
静态代理模式
public class jintaidaili {
public static void main( String[] args ){
A a = new A ();
poxy poxy = new poxy (a);
poxy.start ();
}
}
class A implements Runnable{
@Override
public void run() {
System.out.println ("我是A哦");
}
}
class poxy implements Runnable{
Runnable runnable = null;
@Override
public void run() {
if (runnable != null){
runnable.run ();
}
}
public poxy( Runnable runnable ) {
this.runnable = runnable;
}
public void start(){
start0();
}
private void start0() {
run();
}
}
继承Thread 和实现runnable接口的区别
控制线程结束的方法
设置一个bollean类型的loop
class cat extends Thread{
private int time = 0;
private boolean loop = true;
@Override
public void run() {
while (loop) {
System.out.println (Thread.currentThread ().getName () + (++time));
try {
Thread.sleep (100);
} catch (InterruptedException e) {
e.printStackTrace ();
}
}
}
public void setLoop( boolean loop ) {
this.loop = loop;
}
}
常用方法
interrupt中断休眠
setPriority设置优先级
setdaemon
public static void main( String[] args ) throws InterruptedException {
B322 b322 = new B322 ();
b322.setDaemon (true);
b322.start ();
for (int i = 0; i < 3; i++) {
Thread.sleep (1000);
System.out.println ("妈妈没回家");
}
}
}
class B322 extends Thread {
@Override
public void run() {
while (true) {
try {
Thread.sleep (1000);
} catch (InterruptedException e) {
e.printStackTrace ();
}
System.out.println ("我在打游戏");
}
}