One, run () and start ()
Both methods should be familiar, putting code that requires parallel processing in the run () method, and the start () method starts the thread to automatically invoke the run () method, as defined by the Java memory mechanism. and the run () method must be public access and the return value type is void.
Second, the key word synchronized
This keyword is used to protect shared data, but the prerequisite is to distinguish between which data is shared data. Each object has a lock flag, and when a thread accesses the object, the data decorated by the synchronized is "locked" to prevent other threads from accessing it. When the current thread has finished accessing this part of the data, the lock flag is released and other threads are accessible.
public ThreadTest implements Runnable
{
public synchronized void run(){
for(int i=0;i<10;i++)
{
System.out.println(" " + i);
}
}
public static void main(String[] args)
{
Runnable r1 = new ThreadTest();
Runnable r2 = new ThreadTest();
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
}
The I variables in this program are not shared data, which means that the synchronized keyword here doesn't work. Because t1,t2 two threads are threads of two objects (R1,R2). Different objects have different data, so the I variable of the R1 and R2 two objects is not shared data.
When the code is changed as follows: The Synchronized keyword works
Runnable r = new ThreadTest ();
thread T1 = new Thread (r);
Thread t2 = new Thread (r);
T1.start ();
T2.start ();