Take a look at an example without thread synchronization, this example is very simple, just let two threads output the same content, do not do other things, so, thread synchronization is not obvious here.
Import Java.util.Date;
public class ThreadTest extends thread{int pausetime;
String name;
/** * @param args */public static void main (string[] args) {//TODO auto-generated method stub
ThreadTest tT1 = new ThreadTest (1000, "Thread1");
Tt1.start ();
ThreadTest tT2 = new ThreadTest (3000, "Thread2");
Tt2.start ();
Public threadtest (int pausetime, String name) {this.pausetime = Pausetime;
THIS.name = name;
@Override public void Run () {//TODO auto-generated Method Stub Super.run (); while (true) {try {System.out.println (name + ":" + new Date
(System.currenttimemillis ()));
Thread.Sleep (Pausetime);
catch (Exception e) {//Todo:handle Exception e.printstacktrace (); }
}
}
}
In view of the problem of a multithreaded ticketing, this example shows the importance of thread synchronization, and does not guarantee that this will lead to incorrect execution results
Class Ticketsouce implements Runnable
{
//total number of votes
private int ticket=10;
public void Run ()
{
for (int i=1;i<50;i++)
{
if (ticket>0)
{
//hibernate 1s seconds, in order to make the effect more obvious, Otherwise, it might not work
. try {
thread.sleep (1000);
} catch (Interruptedexception e) {
e.printstacktrace ();
}
System.out.println (Thread.CurrentThread (). GetName () + "window sell" "+this.ticket--+
Ticket");}
}
Public
class Test {public
static void Main (String args[])
{
ticketsouce mt=new ticketsouce ();
Create three Windows
new Thread (MT, "1") based on train tickets. Start ();
New Thread (MT, "2"). Start ();
New Thread (MT, "3"). Start ();
}
The output is shown in the following illustration: