线程同步问题

来源:互联网 发布:开发php扩展 编辑:程序博客网 时间:2024/04/30 00:22

昨天简单研究了一点线程的同步问题

 

 

package com.pb.thread;

public class WayMakeThread {

 public static void main(String[] args) {
  //创建并启动线程
  MyThread mt=new MyThread();
  mt.start();
  
  MyRunable mr=new MyRunable();
  Thread t=new Thread(mr);
  t.start();
 
 }
}
//创建一个线程,继承Thread类
class MyThread extends Thread{
 Printer p=new Printer();
 @Override
 public void run() {
  while(true){
  p.print1();  
  }
 } 
}
//创建一个类,实现Runable接口,这不是一个线程类
class MyRunable implements Runnable{
 Printer p=new Printer();
 @Override
 public void run() {
  while(true){
  p.print2();
  
  }
 }
}
//定义一个普通类
class Printer{
 public void print1(){
  synchronized(Printer.class){
  System.out.print("刘");
  System.out.print("文");
  System.out.print("举");
  System.out.println();
  }
  }
  
 public  void print2(){
  synchronized(Printer.class){
  System.out.print("li");
  System.out.print("xiao");
  System.out.print("xue");
  System.out.println();
  }
 }
}

 

线程类对象的创建有两种方式:

一、继承Thread类子类直接创建对象(MyThread mt=new MyThread())

二、在Thread类中传递一个实现了Runable接口的对象(Thread t=new Thread(new MyRunable()))

线程同步有两种方式:

一、同步方法:方法前加一个synchronized关键字

二、同步代码块:语法格式为synchronized(Object o){要同步的代码块}

 

同步代码块要使用一个同步锁,这个锁可以是任何实体对象,但是如果两个方法需要同步,他们的锁必须相同。即obj的引用必须是同一个引用。

同步方法中也有对象锁,非静态方法中的锁默认为this,静态方法的锁默认为方法所在的类的.class字节码文件。因此在同步代码块中的锁可以使用this或者.class字节码文件。非静态方法中也可以使用类文件作为锁,以上的程序可以达到同步效果。