1,多线程有两种实现方法。
一种是继承Thread类,一种是实现Runnable接口!
1.1,一种是继承Thread类
public class classA() extends Thread { // 继承Thread类
public void run () { // 覆盖run()方法
system.out.println("multi-thread");
}
pubic static void main(String args[]) {
classA clsA = new classA();
clsA.start(); // 启动线程
}
}
1.2,一种是实现Runnable接口
public class classB() implements Runable { // 实现Runnable接口
public void run() { // 覆盖run()方法
system.out.println("multi-thread");
}
public void main (string args[]) {
classB clsB = new classB();
Thread t1 = new Thread(clsB);
t1.start(); // 启动线程
}
}
2,同步有两种实现方法。
一种同步方法,一种同步代码!分别是synchronized,wait与notify
2.1.一种是用同步代码块
同步代码块就是直接写:synchronized (这里写需要同步的对象){...}
public void main(string args[]){
private Well well;
public class Well() {
system.out.println("Well");
}
sychronized(well){ // 同步代码块
String a = "";
system.out.println(a);
}
public viod methodB(){
system.out.println("methodB");
}
}
2.2.一种是用同步方法
同步方法就是在方法返回类型后面加上synchronized,表示一个方法中的所有代码都是同步代码
public void synchronized add(){ // 同步方法
sleep(100);
sytem.out.println("sleep");
}
文章评论