synchronized
First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.
class Printer
{
// Initial 100 paper are set in Printer
int noOfPaper = 100;
// Synchronized the method for inter-thread communication
synchronized void printingPages(int pages)
{
System.out.println("Printing the Pages");
for(int i = 0; i < 100; i++)
{
// Printing Pages
}
// If balance number of Papers are less than user input
// then wait for addPages() synchronized method
// and printing will resume after that
if (this.noOfPaper < pages)
{
System.out.println("Number of Papers in printer are less");
try
{
System.out.println("Waiting...");
wait();
}
catch (Exception e)
{
}
}
System.out.println("After called notify() method number of Paper : " + this.noOfPaper);
System.out.println("Printing process complete");
}
synchronized void addPages(int noOfPages)
{
// Adding more Papers in Printer;
this.noOfPaper += noOfPages;
// After adding the paper in printer. Notify the Paused thread;
notify();
System.out.println("Notify called but thread needs 5 more seconds");
// After call notify() method lock will be give up after 5 seconds
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class MainClass
{
public static void main(String args[])
{
Printer printer = new Printer();
// create two new thread and start them simultaneously
// First thread for print the pages
new Thread()
{
@Override
public void run()
{
// User want to print 120 pages
printer.printingPages(120);
}
}.start();
// Second thread for Add pages in printer
new Thread()
{
@Override
public void run()
{
// Add 100 more pages in Printer
printer.addPages(100);
}
}.start();
}
}
输出为:
Printing the Pages
Number of Papers in printer are less
Waiting…
Notify called but thread needs 5 more seconds
After called notify() method number of Paper : 200
Printing process complete
synchronized和notify、wait结合
The synchronized keyword is used for exclusive accessing.
wait() instructs the calling thread to shut down the monitor and sleep until another thread enters the monitor and calls notify().
notify() wakes up the first thread that called wait() on the same object.
public class MyThread implements Runnable {
private String name;
private Object prev;
private Object self;
private MyThread(String name, Object prev, Object self) {
this.name = name;
this.prev = prev;
this.self = self;
}
public void run() {
int count = 5;
while (count > 0) {
synchronized (prev) {
synchronized (self) {
System.out.print(name);
count--;
self.notify();
}
try {
prev.wait();
} catch (InterruptedException e) {
e.printStackT\frace();
}
}
}
System.exit(0);//退出jvm
}
public static void main(String[] args) throws Exception {
Object a = new Object();
Object b = new Object();
MyThread ta = new MyThread("A", b, a);
MyThread tb = new MyThread("B", a, b);
new Thread(ta).start();
Thread.sleep(100); //确保按顺序A、B执行
new Thread(tb).start();
Thread.sleep(100);
}
}
// Java program to Illustrate notify() method in Thread
// Synchronization.
// Importing required classes
import java.io.*;
import java.util.*;
// Class 1
// Thread1
// Helper class extending Thread class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating object(thread) of class 2
Thread2 objB = new Thread2();
// Starting the thread
objB.start();
synchronized (objB)
{
// Try block to check for exceptions
try {
// Display message only
System.out.println(
"Waiting for Thread 2 to complete...");
// wait() method for thread to be in waiting
// state
objB.wait();
}
// Catch block to handle the exceptions
catch (InterruptedException e) {
// Print the exception along with line
// number using printStackTrace() method
e.printStackTrace();
}
// Print and display the total threads on the
// console
System.out.println("Total is: " + objB.total);
}
}
}
// Class 2
// Thread2
// Helper class extending Thread class
class Thread2 extends Thread {
int total;
// run() method which is called automatically when
// start() is initiated for the same
// @Override
public void run()
{
synchronized (this)
{
// iterating over using the for loo
for (int i = 0; i < 10; i++) {
total += i;
}
// Waking up the thread in waiting state
// using notify() method
notify();
}
}
}