防止线程干扰。
为防止一致性问题。
进程同步
线程同步
互斥 同步方法。 同步块。 静态同步。
合作(java中的线程间通信)
通过同步方法
通过同步块
通过静态同步
class Table{
void printTable(int n){
//method not synchronized for(int i=1;
i<
=5;
i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}
catch(Exception e){
System.out.println(e);
}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
class TestSynchronization1{
public static void main(String args[]){
Table obj = new Table();
//only one objectMyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output: 5 100 10 200 15 300 20 400 25 500
//example of java synchronized methodclass Table{
synchronized void printTable(int n){
//synchronized method for(int i=1;
i<
=5;
i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}
catch(Exception e){
System.out.println(e);
}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronization2{
public static void main(String args[]){
Table obj = new Table();
//only one objectMyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output: 5 10 15 20 25 100 200 300 400 500
//Program of synchronized method by using annonymous classclass Table{
synchronized void printTable(int n){
//synchronized method for(int i=1;
i<
=5;
i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}
catch(Exception e){
System.out.println(e);
}
}
}
}
public class TestSynchronization3{
public static void main(String args[]){
final Table obj = new Table();
//only one objectThread t1=new Thread(){
public void run(){
obj.printTable(5);
}
}
;
Thread t2=new Thread(){
public void run(){
obj.printTable(100);
}
}
;
t1.start();
t2.start();
}
}
Output: 5 10 15 20 25 100 200 300 400 500
Java 同步块
Java 线程静态同步
Java 线程死锁
Java 线程间通信
Java 中断线程