java多线程编程核心技术学习-1

时间:2022-02-22 16:12:38

实现多线程的两种方式

继承Thread类,重写Thread类中的run方法

public class MyThread extends Thread{
@Override
public void run(){
super.run();
System.out.println("this is myThread run");
}
}
public static void main(String[] args) {
Thread myThread=new MyThread();
myThread.start();
System.out.println("mian function is over");
}

注意:代码的顺序并不是线程的执行顺序,start的顺序也不是多个线程的执行顺序。

实现Runable接口

java是单继承的,一个子类只能去继承一个父类,所以如果线程类已经继承了其他父类,那么就不能采用继承thread类来实现多线程了

public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("this is myrunable running");
}
}
public class Test {
public static void main(String[] args) {
Runnable myRunnable=new MyRunnable();
Thread thread=new Thread(myRunnable);
thread.start();
System.out.println("main is runing");
}
}

 实例变量与线程安全

数据不共享的实例,两个线程中分别创建了两个thread实例,各种都是独立的count

public class MyThread extends Thread{
private int count=5;
public MyThread(String name) {
super();
this.setName(name);
}
@Override
public void run(){
super.run();
while(count>0){
count--;
System.out.println(this.currentThread().getName());
System.out.println(count);
}
}
}
public class Test {
public static void main(String[] args) {
Thread thread1=new MyThread("A");
Thread thread2=new MyThread("B");
thread1.start();
thread2.start();
}
}

数据共享的实例

public class MyThread extends Thread {
private int count = 5;
@Override
public void run() {
super.run();
count--;
System.out.println(this.currentThread().getName()+count);
}
}
public class Test {
public static void main(String[] args) {
Thread thread=new MyThread(); Thread thread1=new Thread(thread, "A");
Thread thread2=new Thread(thread,"B");
Thread thread3=new Thread(thread, "C");
thread1.start();
thread2.start();
thread3.start();
}
}

可以在方法上加同步锁,syschronized,这样每一个线程在执行这个方法前需要先尝试去获取这把锁,获取不到就会等待,一直到获取到。

public class MyThread extends Thread {
private int count = 5;
@Override
synchronized public void run() {
super.run();
count--;
System.out.println(this.currentThread().getName()+count);
}
}

下面是一个多线程非安全对的共享变量实例:

在实例*享了静态变量usanameRef和passwordRef

public class Alogin extends Thread{
@Override
public void run(){
LoginServlet.doPost("a", "aa");
}
}
public class Blogin extends Thread{
@Override
public void run(){
LoginServlet.doPost("b", "bb");
}
}
public class LoginServlet {
private static String usenameRef;
private static String passwordRef;
synchronized public static void doPost(String usename,String password){
try {
usenameRef=usename; if(usename.equals("a")){
Thread.sleep(2000);
}
passwordRef=password;
System.out.println("username="+usenameRef+"password="+password);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class Test {
public static void main(String[] args) {
Alogin alogin=new Alogin();
alogin.start();
Blogin blogin=new Blogin();
blogin.start();
}
}

参考: 《java多线程编程核心技术》

https://blog.csdn.net/iaiti/article/details/53314149