Java中线程的同步方法(线程必须是同一个同步方法)

package cn.com.secn.thead;

class Printer
{
	synchronized void printChar(String ch)
	{
		for (int i = 1; i <= 10; i++)
		{
			System.out.print(ch);
		}
	}
}

class MyThead extends Thread
{
	private String ch;
	private Printer printer;

	public MyThead(String ch, Printer printer)
	{
		this.ch = ch;
		this.printer = printer;
	}

	public void run()
	{

		for (int i = 1; i <= 5; i++)
		{
			printer.printChar(ch);
			System.out.println();
		}

	}
}

public class TheadMain
{
	public static void main(String[] args)
	{
		Printer printer = new Printer();
		MyThead thread1 = new MyThead("A",printer);
		MyThead thread2 = new MyThead("B",printer);
		MyThead thread3 = new MyThead("C",printer);
		thread1.start();
		thread2.start();
		thread3.start();
	}
}

你可能感兴趣的:(Java中线程的同步方法(线程必须是同一个同步方法))